Builder模式使用于:需要构造的对象比较复杂或变化较多,而且可以分成若干步骤的。 一个情景如下:
你需要发明一台机器,这个机器可以为每一个旅游的人打印一份计划出来,这个计划是多种多样,每个人的计划又不同。如下图所示:
那这个计划如何生成? 种类这么多,使用的人这么多,这时候可以使用生成者模式代码如下:
//Builder.java
package com.facaizhu;
import java.util.Date;
interface Builder {
void buildDay();
void addHotel(String hotelName);
void addRestaurant(String resName);
void addSpecialEvent(String eventName);
void addTickets(String itemName);
Planner getVocationPlanner();
}
class VocationBuilder implements Builder {
private Planner planner;
public VocationBuilder() {
planner = new Planner();
}
@Override
public void buildDay() {
planner.setDate(new Date());
}
@Override
public void addHotel(String hotelName) {
planner.setHotelName(hotelName);
}
@Override
public void addRestaurant(String resName) {
planner.setResName(resName);
}
@Override
public void addSpecialEvent(String eventName) {
planner.setSpecialEventName(eventName);
}
@Override
public void addTickets(String itemName) {
planner.setItemNameofTicket(itemName);
}
@Override
public Planner getVocationPlanner() {
return planner;
}
}
//Planner.java
package com.facaizhu;
import java.util.Date;
public class Planner {
private Date date;
private String hotelName;
private String resName;
private String specialEventName;
private String itemNameofTicket;
public void printPlan() {
if(null != date)
System.out.println("Date:" + date);
if(null != hotelName)
System.out.println("Hotel: " + hotelName);
if(null != resName)
System.out.println("Restaurant: " + resName);
if(null != specialEventName)
System.out.println("SpecialEvent: " + specialEventName);
if(null != itemNameofTicket)
System.out.println("Ticket: " + itemNameofTicket);
}
public void setDate(Date date) {
this.date = date;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public void setResName(String resName) {
this.resName = resName;
}
public void setSpecialEventName(String specialEventName) {
this.specialEventName = specialEventName;
}
public void setItemNameofTicket(String itemNameofTicket) {
this.itemNameofTicket = itemNameofTicket;
}
}
//PlanDirector.java
package com.facaizhu;
//在这里PlanDirector,其实也就是Client
public class PlanDirector {
public static void main(String[] args) {
Builder builder = new VocationBuilder();
builder.buildDay();
builder.addRestaurant("XXX");
builder.addSpecialEvent("Fly");
Planner planner = builder.getVocationPlanner();
planner.printPlan();
}
}
//AnotherDirector.java
package com.facaizhu;
public class AnotherDirecotor {
public static void main(String[] args) {
Builder builder = new VocationBuilder();
builder.buildDay();
builder.addHotel("ZZZ");
builder.addRestaurant("YYY");
Planner planner = builder.getVocationPlanner();
planner.printPlan();
}
}