Design mode nine, builder mode

Builder mode:
Separate the construction of a complex object from its representation, so that the same construction process can create different representations. Users only need to specify the types that need to be constructed to get them, and the specific construction process and details do not need to be known.

The builder mode is applicable when the algorithm for creating a complex object should be independent of the component parts of the object and their assembly scheme.

//抽象建造者
public interface Builder {
    
    
    public void BuilderPartA();

    public void BuilderPartB();

    public Product GetResult();
}

//具体建造者
public class ConcreteBuilder1 implements Builder {
    
    
    private Product product = new Product();

    /*
    *
    * 建造具体的两个部件A,B
     */
    @Override
    public void BuilderPartA() {
    
    
        product.Add("添加部件A");
    }

    @Override
    public void BuilderPartB() {
    
    
        product.Add("添加部件B");
    }

    @Override
    public Product GetResult() {
    
    
        return product;
    }
}

//具体建造者
public class ConcreteBuilder2 implements Builder {
    
    
    private Product product = new Product();


    /*
     *
     * 建造具体的两个部件X,Y
     */
    @Override
    public void BuilderPartA() {
    
    
        product.Add("添加部件X");
    }

    @Override
    public void BuilderPartB() {
    
    
        product.Add("添加部件Y");
    }

    @Override
    public Product GetResult() {
    
    
        return product;
    }

}

//产品类,由多个部件组成
public class Product {
    
    
    ArrayList<String> parts = new ArrayList<>();

    public void Add(String part) {
    
              //添加产品部件
        parts.add(part);
    }

    public void Show() {
    
            //列举所有产品
        for (String str : parts) {
    
    
            System.out.println(str);
        }
    }
}

//指挥者类
public class Director {
    
    
    /*
     *
     * 用来指挥建造过程
     */
    public void Construct(Builder builder) {
    
    
        builder.BuilderPartA();
        builder.BuilderPartB();
    }

    public static void main(String[] args) {
    
    
        Director director = new Director();
        Builder builder1 = new ConcreteBuilder1();
        Builder builder2 = new ConcreteBuilder2();

        director.Construct(builder1);
        Product product1 = builder1.GetResult();
        product1.Show();

        director.Construct(builder2);
        Product product2 = builder2.GetResult();
        product2.Show();
    }
}

Output:

添加部件A
添加部件B
添加部件X
添加部件Y

Guess you like

Origin blog.csdn.net/weixin_45401129/article/details/114629380