1. 程式人生 > >【設計模式】生成器模式

【設計模式】生成器模式

模式定義

生成器模式將一個複雜物件的構建與它的表示分離,封裝了一個產品的構造過程,並允許按步驟構造。

下圖是該模式的類圖:
生成器模式類圖

一個生動的例子

Product類:
public class Vacation {
	private int day;
	private String hotel;
	private String ticket;
	private String specialEvent;

	public int getDay() {
		return day;
	}

	public void setDay(int day) {
		this.day = day;
} public String getHotel() { return hotel; } public void setHotel(String hotel) { this.hotel = hotel; } public String getTicket() { return ticket; } public void setTickets(String ticket) { this.ticket = ticket; } public String getSpecialEvent() { return specialEvent; } public
void setSpecialEvent(String specialEvent) { this.specialEvent = specialEvent; } @Override public String toString() { return "Vacation [day=" + day + ", hotel=" + hotel + ", ticket=" + ticket + ", specialEvent=" + specialEvent + "]"; } }
Builder抽象類:
public abstract class AbstractBuilder
{ protected Vacation vacation; public Vacation getVocationPlanner() { return vacation; } public AbstractBuilder() { vacation = new Vacation(); } public abstract void buildDay(int day); public abstract void addHotel(String hotel); public abstract void addTicket(String ticket); public abstract void addSpecialEvent(String specialEvent); } Builder實現類: class VacationBuilder extends AbstractBuilder { @Override public void buildDay(int day) { vacation.setDay(day); } @Override public void addHotel(String hotel) { vacation.setHotel(hotel); } @Override public void addTicket(String ticket) { vacation.setTickets(ticket); } @Override public void addSpecialEvent(String specialEvent) { vacation.setSpecialEvent(specialEvent); } }
客戶端類:
public class BuilderTest {
	public static void main(String[] args) {
		AbstractBuilder vacationBuilder = new VacationBuilder();
		vacationBuilder.buildDay(3);
		vacationBuilder.addHotel("hotel");
		vacationBuilder.addSpecialEvent("specialEvent");
		vacationBuilder.addTicket("ticket");
		Vacation vocationPlanner = vacationBuilder.getVocationPlanner();
		System.out.println(vocationPlanner);
	}
}

參考

  1. Head First 設計模式[書籍]
  2. 百度百科之建造者模式
  3. 簡書之生成器模式