建造者模式-builder
故事:
美女:“最近都不太出门,我就画个淡妆。画个眉毛,口红,头发也随便的扎一下。”
代码:
/**
* 不想出门的美女只想随意画个妆,偶尔画个眉毛,有时涂个口红,有时扎个头发
* @author 康康的远方
* @date 2021/4/5
*/
public class Beauty {
private String lip;
private String brow;
private String hair;
private Beauty(Builder builder) {
this.lip = builder.lip;
this.brow = builder.brow;
this.hair = builder.hair;
}
public static class Builder {
private String lip;
private String brow;
private String hair;
public Builder addLip(String lip) {
this.lip = lip;
return this;
}
public Builder addBrow(String brow) {
this.brow = brow;
return this;
}
public Builder addHair(String hair) {
this.hair = hair;
return this;
}
public Beauty build() {
return new Beauty(this);
}
}
}
/**
* @author 康康的远方
* @date 2021/4/5
*/
public class BeautyTest {
public static void main(String[] args) {
Beauty.Builder builder = new Beauty.Builder();
Beauty beauty = builder.addBrow("出门没有画眉毛").addHair("就简单扎了一个头发").build();
System.out.println(beauty);
}
}
思考:设计模式主要是理解他的思想,写法可能稍微优点不同。有的书上Builder是一个接口,定义了我们需要的方法。下面再来一个例子
类图:
代码:
/**
* 建造者顶层抽象类
* @author 康康的远方
* @date 2021/4/5
*/
public abstract class Builder {
public abstract Builder addHair(String hair);
public abstract Builder addBrow(String brow);
public abstract Builder addLip(String lip);
}
/**
* @author 康康的远方
* @date 2021/4/5
*/
public class ConcreteBuilder extends Builder {
private Beauty beauty = new Beauty();
@Override
public ConcreteBuilder addHair(String hair) {
this.beauty.setHair(hair);
return this;
}
@Override
public ConcreteBuilder addBrow(String brow) {
this.beauty.setBrow(brow);
return this;
}
@Override
public ConcreteBuilder addLip(String lip) {
this.beauty.setLip(lip);
return this;
}
public Beauty build(){
return this.beauty;
}
}
/**
* 测试方法
* @author 康康的远方
* @date 2021/4/5
*/
public class BeautyTest {
public static void main(String[] args) {
ConcreteBuilder concreteBuilder = new ConcreteBuilder();
ConcreteBuilder builder = concreteBuilder.addBrow("今天画个淡淡的眉毛").addHair("披头散发");
Beauty beauty = builder.build();
}
}
总结:
当一个类有很多的构造函数时,可以使用建造者模式。我们无法轻易的记住,构造函数不同的传参分别代表什么意思,很难做到见名知意。-------参考《effective Java》