java設計模式學習筆記-構建模式

該模式有4個角色:構建工具接口、構建接口實現類、構建類、產品類

1、產品

package model06.create;

public class Car{
	private String engine;
	private String wheel;
	
	protected Car(String enqine, String wheel){
		this.engine = engine;
		this.wheel = wheel;
	}
	
	protected Car(){
	}
	
	public String getEngine(){
		return engine;
	}
	
	public void setEngine(String engine){
		this.engine = engine;
	}
	
	public String getWheel(){
		return this.wheel;
	}
	
	public void setWheel(String wheel){
		this.wheel = wheel;
	}
}

2、構建者工具接口

package model06.create;

public interface Builder{
	public void buildEngine() throws Exception;
	public void buildWheel() throws Exception;
	public Car getCar() throws Exception;
}

3、構建者工具接口的實現

package model06.create;

public class CarBuilder inplements Builder{
	private String engine;
	private String wheel;
	public void buildEngine() throws Exception{
		this.engine = "engine";
	}
	
	public void buildWheel() throws Exceptino{
		this.wheel = "wheel";
	}
	
	public Car getCar() throws Exception{
		return new Car(engine, wheel);
	}
}

4、構建者類

package model06.create;

public class Director{
	public Builder builder;
	public Director(Builder builder){
		this.builder = builder;
	}
	
	public void constrct() throws Exception{
		if(builder == null){
			throw new RuntimeException("no builder");
		}
		builder.buildEngine();
		builder.buildWheel();
	}
}

構造者模式的優缺點

優點

1:建造模式的使用使得產品的內部表象可以獨立地變化。使用建造模式可以使客戶端不必知道產品內部組成的細節
2:每一個Builder都相對獨立,而與其他的Builder無關
3:模式所建造的最終產品更易於控制

缺點

創建者模式比較符合產品差別不大的對象的創建,如果差別很大,就會導致非常多的具體的創建者,這時候最好結合工廠方法模式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章