package com.example.demo;

public class Client {
    public static void main(String[] args) {
        Builder b=new ConcreteBuilder();
        ConcreteBuilder b1 = new ConcreteBuilder();//建造者
        Director director = new Director(b1);//监工
        director.construct();//建造实例(监工负责监督,建造者实际建造)
        String result = b1.getResult();//获取最终生成结果
        System.out.printf("the result is :%n%s", result);
    }
}
package com.example.demo;

public class ConcreteBuilder extends Builder {
    private StringBuffer buffer = new StringBuffer();//假设 buffer.toString() 就是最终生成的产品
    @Override
    public void buildPart1() {
        buffer.append("Builder1 : Part1\n");
    }

    @Override
    public void buildPart2() {
        buffer.append("Builder2 : Part2\n");
    }

    @Override
    public void buildPart3() {
        buffer.append("Builder3 : Part3\n");
    }
    public String getResult() {//定义获取最终生成实例的方法
        return buffer.toString();
    }
}
package com.example.demo;

public class Director {
    private Builder builder;    // 针对接口编程,而不是针对实现编程
    public Director(Builder builder) {
        this.builder = builder;
    }

    public void construct() {   // 控制(定义)一个复杂的构建过程
        builder.buildPart1();
        for (int i = 0; i < 5; i++) {   // 提示:如果想在运行过程中替换构建算法,可以考虑结合策略模式。
            builder.buildPart2();
        }
        builder.buildPart3();
    }
}
package com.example.demo;

public abstract class  Builder {
    public abstract void buildPart1();
    public abstract void buildPart2();
    public abstract void buildPart3();
}