建造者模式 链式编程式

package com.life.design.builder;

public abstract class Builder {
    public abstract Builder buildPartA(String msg);
    public abstract Builder buildPartB(String msg);
    public abstract Builder buildPartC(String msg);
    public abstract Product getProduct();

}
package com.life.design.builder;

public class ConcreteBuilder extends Builder {
    private Product product;

    public ConcreteBuilder() {
        product = new Product();
    }
    @Override
    public Builder buildPartA(String msg) {
        product.setPartA(msg);
        return this;
    }

    @Override
    public Builder buildPartB(String msg) {
        product.setPartB(msg);
        return this;
    }

    @Override
    public Builder buildPartC(String msg) {
        product.setPartC(msg);
        return this;
    }

    @Override
    public Product getProduct() {
        return product;
    }
}
package com.life.design.builder;

public class Product {
    private String partA = "地基";
    private String partB = "扎钢筋";
    private String partC = "浇筑";

    public String getPartA() {
        return partA;
    }

    public void setPartA(String partA) {
        this.partA = partA;
    }

    public String getPartB() {
        return partB;
    }

    public void setPartB(String partB) {
        this.partB = partB;
    }

    public String getPartC() {
        return partC;
    }

    public void setPartC(String partC) {
        this.partC = partC;
    }

    @Override
    public String toString() {
        return "Product{" +
                "partA='" + partA + '\'' +
                ", partB='" + partB + '\'' +
                ", partC='" + partC + '\'' +
                '}';
    }
}
package com.life.design.builder;

public class Test {
    public static void main(String[] args) {
        Builder builder = new ConcreteBuilder();
        Product product = builder
                .buildPartA("A")
                .buildPartB("B")
                .buildPartC("C")
                .getProduct();
        System.out.println(product);
    }
}

 

posted on 2022-04-17 16:55  金满仓  阅读(23)  评论(0编辑  收藏  举报

导航