设计模式-建造者模式
别名:创建者模式
建造者模式针对复杂对象,分离它们的构建与表示,达到同样构建过程创建不同表示的目的。
建造者模式封装了复杂对象的构建过程,通过子类继承或者重载的方式,动态的创建具有复合属性的对象。
传统模式
就拿做三明治来举例,首先定义三明治的抽象类
@Data
public class Sandwich {
private String bread;
private String meat;
private List<String> veg;
private String source;
public Sandwich(String bread, String meat) {
this.bread = bread;
this.meat = meat;
}
}
然后定义抽象的Builder
public abstract class SandwichBuilder {
public abstract void setVeg();
public abstract void setSource();
public abstract Sandwich getSandwich();
}
现在提供两种实现
public class TunaSandwichBuilder extends SandwichBuilder {
private Sandwich sandwich;
public TunaSandwichBuilder(String bread) {
this.sandwich = new Sandwich(bread, "金枪鱼");
}
@Override
public void setVeg() {
sandwich.setVeg(Arrays.asList("番茄", "黄瓜", "生菜"));
}
@Override
public void setSource() {
sandwich.setSource("番茄酱");
}
@Override
public Sandwich getSandwich() {
return sandwich;
}
}
public class SirloinSandwichBuilder extends SandwichBuilder {
private Sandwich sandwich;
public SirloinSandwichBuilder(String bread) {
this.sandwich = new Sandwich(bread, "牛腩");
}
@Override
public void setVeg() {
sandwich.setVeg(Arrays.asList("青椒", "酱瓜"));
}
@Override
public void setSource() {
sandwich.setSource("千岛酱");
}
@Override
public Sandwich getSandwich() {
return sandwich;
}
}
然后定义一个指挥官
public class SandwichDirector {
public void makeSandwich(SandwichBuilder builder){
builder.setVeg();
builder.setSource();
}
}
调用的时候
public class SandwichMaker {
public static void main(String[] args) {
SandwichDirector director = new SandwichDirector();
SandwichBuilder builder = new TunaSandwichBuilder("燕麦面包");
director.makeSandwich(builder);
Sandwich tunaSandwich = builder.getSandwich();
System.out.println(tunaSandwich);
builder = new SirloinSandwichBuilder("全麦面包");
director.makeSandwich(builder);
Sandwich sirSandwich = builder.getSandwich();
System.out.println(sirSandwich);
}
}
类JDK8的Builder
对类Sandwich做改造
@ToString
public class Sandwich {
private String bread;
private String meat;
private List<String> veg;
private String source;
private Sandwich(Builder builder) {
this.bread = builder.bread;
this.meat = builder.meat;
this.veg = builder.veg;
this.source = builder.source;
}
public static class Builder{
private String bread;
private String meat;
private List<String> veg;
private String source;
public Builder(String bread, String meat) {
this.bread = bread;
this.meat = meat;
}
public Builder veg(List<String> veg){
this.veg = veg;
return this;
}
public Builder source(String source){
this.source = source;
return this;
}
public Sandwich build(){
return new Sandwich(this);
}
}
}
调用时就可以使用连续构造的哲学
public class BuildDemo {
public static void main(String[] args) {
Sandwich sandwich = new Sandwich.Builder("蜂蜜面包", "鸡胸肉")
.veg(Arrays.asList("洋葱", "胡萝卜")).source("BBQ").build();
System.out.println(sandwich);
}
}