它有啥用
它用于解決,通過變化無常的方式,來組織相對不變的構成要素,形成一個整體對象的問題。再強調一遍,變化的是方式,不變的是構成要素。
這種模式就是把方式和構成要素分開處理了。
其中指揮員負責不同的組裝方式。
其實這就好比木炭和金剛石都是碳元素的單質,只是因為分子結構不同結果形成了不同的物質一樣。
類圖
建造者模式.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();
}
}