建造者模式

2018-10-13  本文已影响33人  Stroman

它有啥用

它用于解决,通过变化无常的方式,来组织相对不变的构成要素,形成一个整体对象的问题。再强调一遍,变化的是方式,不变的是构成要素。
这种模式就是把方式和构成要素分开处理了。
其中指挥员负责不同的组装方式。
其实这就好比木炭和金刚石都是碳元素的单质,只是因为分子结构不同结果形成了不同的物质一样。

类图

建造者模式.png

效果

组件0由SomeBuilder制造
组件1由SomeBuilder制造
组件2由SomeBuilder制造
生产产品
组件2由SomeBuilder制造
组件1由SomeBuilder制造
组件0由SomeBuilder制造
生产产品

Process finished with exit code 0

使用

package com.company;

public class Main {

    public static void main(String[] args) {
    // write your code here
        Director0 director0 = new Director0();
        director0.firstKindOfProduct(new SomeBuilder());

        Director1 director1 = new Director1();
        director1.secondKindOfProduct(new SomeBuilder());
    }
}

通用建造者

package com.company;

public interface CommonBuilder {
    void makeComponent0();
    void makeComponent1();
    void makeComponent2();
    Product gainProduct();
}

产品

package com.company;

public class Product {
    private String component0;
    private String component1;
    private String component2;

    public String getComponent0() {
        return component0;
    }

    public void setComponent0(String component0) {
        this.component0 = component0;
    }

    public String getComponent1() {
        return component1;
    }

    public void setComponent1(String component1) {
        this.component1 = component1;
    }

    public String getComponent2() {
        return component2;
    }

    public void setComponent2(String component2) {
        this.component2 = component2;
    }
}

某个具体的建造者

package com.company;

public class SomeBuilder implements CommonBuilder {
    private Product product;

    public SomeBuilder() {
        this.product = new Product();
    }

    @Override
    public void makeComponent0() {
        this.product.setComponent0("组件0由SomeBuilder制造");
        System.out.println(this.product.getComponent0());
    }

    @Override
    public void makeComponent1() {
        this.product.setComponent1("组件1由SomeBuilder制造");
        System.out.println(this.product.getComponent1());
    }

    @Override
    public void makeComponent2() {
        this.product.setComponent2("组件2由SomeBuilder制造");
        System.out.println(this.product.getComponent2());
    }

    @Override
    public Product gainProduct() {
        System.out.println("生产产品");
        return this.product;
    }
}

指挥者

package com.company;

public class Director0 {
    public Product firstKindOfProduct(CommonBuilder builder) {
        builder.makeComponent0();
        builder.makeComponent1();
        builder.makeComponent2();
        return builder.gainProduct();
    }
}

另一个指挥者

package com.company;

public class Director1 {
    public Product secondKindOfProduct(CommonBuilder builder) {
        builder.makeComponent2();
        builder.makeComponent1();
        builder.makeComponent0();
        return builder.gainProduct();
    }
}

上一篇下一篇

猜你喜欢

热点阅读