在工作中我們經(jīng)常遇到參數(shù)比較多的構(gòu)造函數(shù)白对,構(gòu)造函數(shù)的參數(shù)可能很快就會失控怔匣,而且可能很難理解每個參數(shù)击胜。如果將來你想添加參數(shù),或者改變參數(shù)役纹,這個參數(shù)列表還可能更快增長偶摔,很容易出錯。例如生成下面的“英雄”角色促脉,選擇職業(yè)辰斋、性別、頭發(fā)顏色等瘸味,角色的生成就變成了一個一步一步的過程宫仗,當所有的選擇都準備好了,這個過程就完成了旁仿。
public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) {
}
我們可以利用java中的構(gòu)造者設計模式進行重構(gòu)藕夫,首先有我們想要的“英雄”。
public final class Hero {
private final Profession profession;
private final String name;
private final HairType hairType;
private final HairColor hairColor;
private final Armor armor;
private final Weapon weapon;
private Hero(Builder builder) {
this.profession = builder.profession;
this.name = builder.name;
this.hairColor = builder.hairColor;
this.hairType = builder.hairType;
this.weapon = builder.weapon;
this.armor = builder.armor;
}
}
然后是建造者:
public static class Builder {
private final Profession profession;
private final String name;
private HairType hairType;
private HairColor hairColor;
private Armor armor;
private Weapon weapon;
public Builder(Profession profession, String name) {
if (profession == null || name == null) {
throw new IllegalArgumentException("profession and name can not be null");
}
this.profession = profession;
this.name = name;
}
public Builder withHairType(HairType hairType) {
this.hairType = hairType;
return this;
}
public Builder withHairColor(HairColor hairColor) {
this.hairColor = hairColor;
return this;
}
public Builder withArmor(Armor armor) {
this.armor = armor;
return this;
}
public Builder withWeapon(Weapon weapon) {
this.weapon = weapon;
return this;
}
public Hero build() {
return new Hero(this);
}
}
然后調(diào)用方法:
var mage = new Hero.Builder(Profession.MAGE, "Riobard")
.withHairColor(HairColor.BLACK)
.withWeapon(Weapon.DAGGER).build();
類圖:
builder.png
Real world examples
- java.lang.StringBuilder
- java.nio.ByteBuffer as well as similar buffers such as FloatBuffer, IntBuffer and so on.
- java.lang.StringBuffer
- All implementations of java.lang.Appendable
- Apache Camel builders
- Apache Commons Option.Builder