设计模式-构造器模式

类图

 

实现代码

Director

class Director {
    private Builder builder;
    public Director(Builder builder) {
         this.builder = builder;
    }
    public void construct() {
        builder.buildPartA();
        builder.buildPartB();
    }
}

Builder.class

interface Builder {
    void buildPartA();
    void buildPartB();
    Product getResult();
}

BuilderA.class

class BuilderA implements Builder {
    private Product productA;
    public BuilderA(Product productA) {
        this.productA = productA;
    }

    public void buildPartA() {
        this.productA.setHead("型号1");
    }

    public void buildPartB() {
        this.productA.setBody("A工产生产");
    }

    public Product getResult() {
        return productA;
    }
}

Product.class

class Product {
    private String head;
    private String body;

    get set..
}

Test.class

public class TestBuilder {
    public static void main(String[] args) {
        BuilderA builderA = new BuilderA(new Product());
        Director director = new Director(builderA);
        director.construct();
        System.out.println(builderA.getResult());
    }
}

  

  

 

  

  

  

 

posted @ 2022-02-11 11:49  hy叶子  阅读(40)  评论(0编辑  收藏  举报