定义
建造者模式(Builder Pattern)也叫做生成器模式,其定义如下:
Separate the construction of a complex object from its representation so that the same construction process can create different representations.(将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。)
示例
以构建一个人示例,灵魂是必须有的,肢体可有可无,哈哈
复用构造器
public class Person {
private String foot;
private String head;
private String face;
private String hand;
private String soul;
public Person(String soul) {
this(null,null,null,null,soul);
}
public Person(String hand, String soul) {
this(null,null,null,hand,soul);
}
public Person(String foot, String face, String soul) {
this(foot,null,face,null,soul);
}
public Person(String foot, String head, String face, String hand, String soul) {
this.foot = foot;
this.head = head;
this.face = face;
this.hand = hand;
this.soul = soul;
}
}
参数一旦多了,阅读起来就很麻烦,要理解每个参数的意思,而且一不小心还会传错
使用构造者模式
public class Person {
private String foot;
private String head;
private String face;
private String hand;
private String soul;
private Person(Builder builder) {
this.foot = builder.foot;
this.head = builder.head;
this.face = builder.face;
this.hand = builder.hand;
this.soul = builder.soul;
}
@Override
public String toString() {
return "Builder{" +
"foot='" + foot + '\'' +
", face='" + face + '\'' +
", head='" + head + '\'' +
", hand='" + hand + '\'' +
", soul='" + soul + '\'' +
'}';
}
public static final class Builder{
private String foot;
private String face;
private String head;
private String hand;
private String soul;
public Builder(String soul) {
this.soul = soul;
}
public Person build(){
return new Person(this);
}
public Builder foot(String foot) {
this.foot = foot;
return this;
}
public Builder head(String head) {
this.head = head;
return this;
}
public Builder face(String face) {
this.face = face;
return this;
}
public Builder hand(String hand) {
this.hand = hand;
return this;
}
}
}
public class Client {
public static void main(String[] args) {
Person person = new Person.Builder("我的灵魂").face("脸庞").foot("大脚").build();
System.out.println(person);
}
}
"C:\Program Files\Java\jdk1.8.0_144\bin\java.exe" "-javaagent:D:\IntelliJ IDEA\IntelliJ IDEA 2018.2.4\lib\idea_rt.jar=61032:D:\IntelliJ IDEA\IntelliJ IDEA 2018.2.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_144\jre\lib\charsets.jar;C:\Program bin\rep\org\springframework\spring-beans\5.2.12.RELEASE\spring-beans-5.2.12.RELEASE.jar;D:\apache-maven-3.5.4-bin\rep\org\springframework\spring-core\5.2.12.RELEASE\spring-core-5.2.12.RELEASE.jar;D:\apache-maven-3.5.4-bin\rep\org\springframework\spring-jcl\5.2.12.RELEASE\spring-jcl-5.2.12.RELEASE.jar;D:\apache-maven-3.5.4-bin\rep\org\slf4j\slf4j-api\1.7.30\slf4j-api-1.7.30.jar"
Builder{foot='大脚', face='脸庞', head='null', hand='null', soul='我的灵魂'}
Process finished with exit code 0
结合链式调用,使用起来特别直观,不易出错
建造者模式的优缺点
优点
- 封装性,客户端不必知道产品内部组成的细节
- 便于控制细节风险。可以对建造过程逐步细化,而不对其他模块产生任何影响。
缺点
- 产品必须有共同点,范围有限制
使用场景
- 产品类非常复杂,或者产品类中的调用顺序不同产生了不同的效能
- 多个部件或零件,都可以装配到一个对象中,但是产生的运行结果又不相同时
- 相同的方法,不同的执行顺序,产生不同的事件结果