使用生成器模式封装一个产品的构造过程,并允许按步骤构造。
示例—度假计划
需要为每位客人定制度假计划。由于客人的不同需求,客人自己可以选择旅馆以及各种门票、餐厅订位,甚至也可以选择登记参加特殊的活动。每个客人的度假计划可能都不一样,例如天数、活动类型。比方说,当地居民可能不需要旅馆,但是想要用餐并参与特殊活动。而其他的客人可能是从外地飞过来的,所以需要旅馆、用餐和门票。
UML图表示
生成器模式-度假计划代码演示
计划类
package Builder;
public class Planner {
Planner(){
plan = new StringBuilder();
}
private StringBuilder plan;
public String getPlan() {
return plan.toString();
}
public void addEvent(String event) {
this.plan.append(event);
plan.append("\n");
}
}
生成计划的接口
package Builder;
public interface AbstractBuilder {
void buildDay(String date);
void addHotel(String date, String hotel);
void addReservation(String reservation);
void addSpecialEvent(String event);
void addTickets(String tickets);
Planner getVacationPlanner();
}
生成计划实现类
package Builder;
public class VacationBuilder implements AbstractBuilder {
Planner vacation;
VacationBuilder(){
vacation = new Planner();
}
@Override
public void buildDay(String date) {
vacation.addEvent("Your plan is in " + date + ". ");
}
@Override
public void addHotel(String date, String hotel) {
vacation.addEvent("Checking in "+ hotel + " hotel at " + date + ". ");
}
@Override
public void addReservation(String reservation) {
vacation.addEvent("Your " + reservation + " was reserved. ");
}
@Override
public void addSpecialEvent(String event) {
vacation.addEvent("You are enjoying " + event + ". ");
}
@Override
public void addTickets(String tickets) {
vacation.addEvent("You'll have tickets of " + tickets + ". ");
}
@Override
public Planner getVacationPlanner() {
return vacation;
}
}
客户类
package Builder;
public class Client {
Planner constructPlanner(){
AbstractBuilder builder = new VacationBuilder();
builder.buildDay("2017-10-01");
builder.addHotel("2017-10-01","Super Star");
builder.addReservation("a Mexican restaurant ");
builder.addSpecialEvent("New Year Concert");
builder.addTickets("Pattems on Ice");
return builder.getVacationPlanner();
}
String showPlan(){
return constructPlanner().getPlan();
}
}
测试代码
package Builder;
public class BuilderDriver {
public static void main(String[] args) {
Client C1 = new Client();
System.out.println("The Plan for C1: ");
System.out.println(C1.showPlan());
}
}
测试结果
The Plan for C1:
Your plan is in 2017-10-01.
Checking in Super Star hotel at 2017-10-01.
Your a Mexican restaurant was reserved.
You are enjoying New Year Concert.
You'll have tickets of Pattems on Ice.
网友评论