1.意图
将复杂对象的构造与其表示分开,使得相同的构造过程可以创建不同的表示。
2.解释
允许您创建不同风格的对象,同时避免构造器污染。 当有可能有几种口味的对象时很有用。 或者当创建对象时涉及很多步骤。
构建器模式是一种对象创建软件设计模式,其目的是找到伸缩构造器反模式的解决方案。
3.使用场景
- 用于创建复杂对象的算法应该独立于构成对象的部件以及它们的组合方
- 构造过程必须允许构建的对象的不同表示
4.代码实例
public class Hero {
private final String profession;
private final String name;
private final String weapon;
private final String hairType;
private final String hairColor;
private Hero(Builder builder) {
this.profession = builder.profession;
this.name = builder.name;
this.hairColor = builder.hairColor;
this.hairType = builder.hairType;
this.weapon = builder.weapon;
}
public static class Builder {
private final String profession;
private final String name;
private String weapon;
private String hairType;
private String hairColor;
public Builder(String name, String profession) {
if (name == null || profession == null) {
throw new IllegalArgumentException("profession and name can not be null");
}
this.profession = profession;
this.name = name;
}
public Builder withHairType(String hairType) {
this.hairType = hairType;
return this;
}
public Builder withHairColor(String hairColor) {
this.hairColor = hairColor;
return this;
}
public Builder withWeapon(String weapon) {
this.weapon = weapon;
return this;
}
public Hero build() {
return new Hero(this);
}
}
@Override
public String toString() {
return "Hero{" +
"profession='" + profession + '\'' +
", name='" + name + '\'' +
", weapon='" + weapon + '\'' +
", hairType='" + hairType + '\'' +
", hairColor='" + hairColor + '\'' +
'}';
}
}
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
Hero hero = new Hero.Builder("Jack", "Riobard").withHairColor("Black").build();
logger.info(hero.toString());
}
}
参考教程:https://github.com/iluwatar/java-design-patterns/tree/master/builder