Builder模式:分步驟構建一個複雜物件,實現複雜物件的建立過程和對象的表示相分離.
不管在軟體系統還是其他領域,有時候會遇到 一個複雜的工程或者對象的建立,而這個建立可能有各個子模組或對象用一定的邏輯或者演算法組成,由於各種原因這個複雜工程或對象各個部分可能需要經常的更新或變化,但是整個組合體或者說這個工程或對象要保證足夠的穩定性.【不會因為子模組變化造成對整個工程巨大影響】 --- this is Bulider's Application environment;
以車為例吧
假設
車 = 輪子 + 外殼 + 發動機
代碼實現:
//車的組件生產和組裝規範
public interface Builder {
void makeWheel();
void makeShell();
void makeEngine();
Car buildCar();
}
//車
public class Car {
public Component getWheel() {
return wheel;
}
public void setWheel(Component wheel) {
this.wheel = wheel;
}
public Component getShell() {
return shell;
}
public void setShell(Component shell) {
this.shell = shell;
}
public Component getEngine() {
return engine;
}
public void setEngine(Component engine) {
this.engine = engine;
}
private Component wheel;
private Component shell;
private Component engine;
public String toString(){return wheel.getColor()+":"+engine.getColor()+":"+shell.getColor();}
}
//車的組成組件
public class Component {
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
//負責車的組裝
public class CarFactory {
private Builder builder;
CarFactory(Builder builder){
this.builder = builder;
}
public void buildCar(){
builder.makeWheel();
builder.makeEngine();
builder.makeShell();
}
}
//負責寶馬車的生產
public class BMWFactory implements Builder {
Component wheel,shell,engine;
public void makeWheel() {
wheel = new Component();
wheel.setColor("red");
}
public void makeShell() {
shell = new Component();
shell.setColor("magnificent");
}
public void makeEngine() {
engine = new Component();
engine.setColor("BMW");
}
public Car buildCar() {
Car bmw = new Car();
bmw.setEngine(engine);
bmw.setShell(shell);
bmw.setWheel(wheel);
return bmw;
}
}
//負責奧迪車的生產
public class AudiFactory implements Builder{
Component wheel,shell,engine;
public void makeWheel() {
wheel = new Component();
wheel.setColor("blue");
}
public void makeShell() {
shell = new Component();
shell.setColor("changpeng");
}
public void makeEngine() {
engine = new Component();
engine.setColor("dongfeng");
}
public Car buildCar() {
Car audi = new Car();
audi.setEngine(engine);
audi.setShell(shell);
audi.setWheel(wheel);
return audi;
}
}
//來買車吧
public class CarShop {
private static Car get(Builder builder){
CarFactory factory = new CarFactory(builder);
factory.buildCar();
return builder.buildCar();
}
/**
* @param args
*/
public static void main(String[] args) {
AudiFactory audiFactory = new AudiFactory();
BMWFactory bmwFactory = new BMWFactory();
Car audi = get(audiFactory);
System.out.println(audi);
Car bmw = get(bmwFactory);
System.out.println(bmw);
}
}
這樣不管車的組件不管變成什麼樣,你可以修改make***的內部邏輯,不會影響到 buildCar ..make***和buildCar 是分離的,
最後總能保證車的穩定生產.