复习:GoF的23种设计模式之Builder模式(创建型)

2019-12-25 16:08:32 浏览数 (1)

Builder模式(生成)

我们创建复杂的对象时,会使用到此Builder模式,定义:它可以将复杂对象的初始化过程 抽象出来,使这个抽象过程的不同实现方法可以构建不同的表现(属性)对象。通过一步步构建,最终完成对象的构建。后面可以与抽象工厂做对比。

其实,还是有点绕,那就先认定一点builder模式==创建复杂对象,再往下看。

灵魂作图

示例代码:

代码语言:javascript复制
public class BuilderTest {
    public static void main(String[] args) {
        Builder builder = new ConcreteBuilder2();
        Director director = new Director(builder);
        director.construct("一个对象:");
        System.out.println(director.getProduct().toString());
        //第二个对象
        Builder builder1 = new ConcreteBuilder1();
        Director director1 = new Director(builder1);
        director1.construct("不同对象:");
        System.out.println(director1.getProduct().toString());
    }
}

class ComPlexProduct {
    private String complexStr ;
    private int plan ;
    public void setComplexStr(String complexStr) {
        this.complexStr = complexStr;
    }
    public void setPlan(int plan) {
        this.plan = plan;
    }
    @Override
    public String toString() {
        return complexStr plan;
    }
}
abstract class Builder {  //构建product提取为抽象方法
    protected ComPlexProduct product;
    public void createProduct() {
        product = new ComPlexProduct();
    }
    public ComPlexProduct getProduct() {
        return product;
    }
    public abstract void setProductStr(String complexStr);
    public abstract void setProductPlan();
}
class ConcreteBuilder1 extends Builder{  //构建一个复杂product
    @Override
    public void setProductStr(String complexStr) {
        product.setComplexStr(complexStr "这有一个构建算法");
    }
    @Override
    public void setProductPlan() {
        product.setPlan(10);
    }
}
class ConcreteBuilder2 extends Builder{
    @Override
    public void setProductStr(String complexStr) {
        product.setComplexStr(complexStr "这有一个构建算法,还是非本地的");
    }
    @Override
    public void setProductPlan() {
        product.setPlan((int) (System.currentTimeMillis()));
    }
}
class Director{
    private Builder builder;
    public Director(Builder builder) {
        this.builder = builder;
    }

    public ComPlexProduct getProduct() {
        return builder.getProduct();
    }
    public void construct(String productName) {
        builder.createProduct();
        builder.setProductPlan();
        builder.setProductStr(productName);
    }
}

UML类图

0 人点赞