【设计模式】创建者模式

创建者模式简单示例
1.创建者抽象

public abstract class Builder {
    abstract void builderA();//地基
    abstract void builderB();//钢筋工程
    abstract void builderC();//铺电线
    abstract void builderD();//粉刷

    //完工:得到产品
    abstract Product getProduct();
}

2.创建者实现

/**
 * 具体创建者
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class Worker extends Builder{

    private Product product;
    private String name;
    public Worker(String name){
        this.product=new Product();
        this.name=name;

    }

    @Override
    void builderA() {
        System.out.println(this.name+"打地基");
        product.setBuilderA("地基");
    }

    @Override
    void builderB() {
        System.out.println(this.name+"扎工程");
        product.setBuilderB("钢筋");
    }

    @Override
    void builderC() {
        System.out.println(this.name+"铺电线");
        product.setBuilderC("电线");
    }

    @Override
    void builderD() {
        System.out.println(this.name+"粉刷");
        product.setBuilderC("粉刷");
    }


    @Override
    Product getProduct() {
        System.out.println("建房完成");
        return product;
    }
}

3.创建成果

/**
 * 产品--房子
 */

@Data
public class Product{
    private String builderA;
    private String builderB;
    private String builderC;
    private String builderD;
}

4.创建指挥者

/**
 * 指挥者
 */
public class Director {

    //指挥工人按照顺序建房子
    public Product build(List<Worker> builders){
        Worker builder = null;
        for (int i = 0; i < builders.size(); i++) {
            builder = builders.get(i);
            switch (i){
                case 0:
                    builder.builderA();
                    break;
                case 1:
                    builder.builderB();
                    break;
                case 2:
                    builder.builderC();
                    break;
                case 3:
                    builder.builderD();
                    break;
            }
        }
        return builder.getProduct();
    }
}

5.测试

 @Test
    void buildTest(){
        Director director = new Director();
        List<Worker> workers = new ArrayList<>();
        workers.add(new Worker("张三"));
        workers.add(new Worker("李四"));
        workers.add(new Worker("王五"));
        workers.add(new Worker("赵六"));
        Product build = director.build(workers);
        System.out.println(build);
    }

6.总结

1.创建者模式适用于 将对象的复杂创建过程封装起来,客户端或者控制层不必关心细节。
2.对构造过程更加精细。

你可能感兴趣的:(设计模式,设计模式,java)