04 设计模式 建造者模式

2020-07-30 17:06:59 浏览数 (1)

建造者模式

建造者模式就好像盖一栋房子,需要有设计师,图纸,施工队以及成品,

在这其中:

  • 设计师负责确定流程
  • 图纸是一个施工的描述
  • 施工队是具体的动作
  • 成品是最后的结果

图例如下:

成品类:

代码语言:javascript复制
@Data
@ToString
public class Product {
    String buildA = "默认值A";
    String buildB = "默认值B";
    String buildC = "默认值C";
    String buildD = "默认值D";
}

上面的成品类就是最终的产品所需要具备的属性,我把它理解为实体类

图纸类:

代码语言:javascript复制
public abstract class Builder {
    abstract Builder buildA(String msg);
    abstract Builder buildB(String msg);
    abstract Builder buildC(String msg);
    abstract Builder buildD(String msg);

    abstract Product getProduct();
}

Builder就是一个对施工队的抽象,也就在一个工程中所需要的步骤,没有具体的实现

施工队类:

代码语言:javascript复制
public class Worker extends Builder{
    Product product;

    Worker(){product = new Product();}

    @Override
    Builder buildA(String msg) {
        product.setBuildA(msg);
        return this;
    }

    @Override
    Builder buildB(String msg) {
        product.setBuildB(msg);
        return this;
    }

    @Override
    Builder buildC(String msg) {
        product.setBuildC(msg);
        return this;
    }

    @Override
    Builder buildD(String msg) {
        product.setBuildD(msg);
        return this;
    }

    @Override
    Product getProduct() {return product;}
}

施工队类是Builder的实现类,确定了Builder中步骤的具体操作

导演类:

代码语言:javascript复制
public class Director {
    public static Product build(Builder builder){
        return builder.getProduct();
    }
    public static Product build(Builder builder, String msg1){
        builder.buildA(msg1).getProduct();
        return builder.getProduct();
    }
    public static Product build(Builder builder, String msg1, String msg2){
        return builder.buildA(msg1).buildB(msg2).getProduct();
    }
    public static Product build(Builder builder, String msg1, String msg2, String msg3){
        return builder.buildA(msg1).buildB(msg2).buildC(msg3).getProduct();
    }
    public static Product build(Builder builder, String msg1, String msg2, String msg3, String msg4){
        return builder.buildA(msg1).buildB(msg2).buildC(msg3).buildD(msg4).getProduct();
    }

}

其用于指导具体的施工队如何施工,控制先后次序等

测试类:

代码语言:javascript复制
public static void main(String[] args) {
        System.out.println(Director.build(new Worker()));
        System.out.println(Director.build(new Worker(),"这是第一个参数"));
        System.out.println(Director.build(new Worker(),"这是第一个参数","这是第二个参数"));
        System.out.println(Director.build(new Worker(),"这是第一个参数","这是第二个参数","这是第三个参数"));
        System.out.println(Director.build(new Worker(),"这是第一个参数","这是第二个参数","这是第三个参数","这是第四个参数"));
    }
}

结果如下:

Product{buildA='默认值A', buildB='默认值B', buildC='默认值C', buildD='默认值D'} Product{buildA='这是第一个参数', buildB='默认值B', buildC='默认值C', buildD='默认值D'} Product{buildA='这是第一个参数', buildB='这是第二个参数', buildC='默认值C', buildD='默认值D'} Product{buildA='这是第一个参数', buildB='这是第二个参数', buildC='这是第三个参数', buildD='默认值D'} Product{buildA='这是第一个参数', buildB='这是第二个参数', buildC='这是第三个参数', buildD='这是第四个参数'}

0 人点赞