设计模式-建造者模式的应用
建造者模式的应用
实例:KFC套餐
建造者模式可以用于描述KFC如何创建套餐:套餐是一个复杂对象,它一般包含主食(如汉堡、鸡肉卷等)和饮料(如果汁、可乐等)等组成部分,不同的套餐有不同的组成部分,而KFC的服务员可以根据顾客的要求,一步一步装配这些组成部分,构造一份完整的套餐,然后返回给顾客。利用建造者模式设计,用JAVA语言实现 (或C#控制台应用程序实现)。绘制该模式的UML图。
【模式UML图】
【模式代码(JAVA语言实现)】
//SetMeal.java:
package sdp.sy_3.builderpattern;
//产品类:套餐――包括主食和饮料
public class SetMeal {
String StapleFood; //主食
String Dringks; //饮料
public String getStapleFood() {
return StapleFood;
}
public void setStapleFood(String stapleFood) {
StapleFood = stapleFood;
}
public String getDringks() {
return Dringks;
}
public void setDringks(String dringks) {
Dringks = dringks;
}
}
// SetMealBuilder.java:
package sdp.sy_3.builderpattern;
//抽象的Builder接口
public abstract class SetMealBuilder {
SetMeal setMeal = new SetMeal();
public abstract void createStapleFood();
public abstract void createDrinks();
public SetMeal getSetMeal() {
return setMeal;
}
}
// SetMealBuilderA.java:
package sdp.sy_3.builderpattern;
//套餐A:主食:汉堡+饮料:果汁
public class SetMealBuilderA extends SetMealBuilder{
@Override
public void createStapleFood() {
setMeal.setStapleFood("Hamburger");
}
@Override
public void createDrinks() {
setMeal.setDringks("juice");
}
}
// SetMealBuilderB.java:
package sdp.sy_3.builderpattern;
//套餐B:主食:鸡肉卷+饮料:可乐
public class SetMealBuilderB extends SetMealBuilder{
@Override
public void createStapleFood() {
setMeal.setStapleFood("ChickenRolls");
}
@Override
public void createDrinks() {
setMeal.setDringks("Cola");
}
}
// Director.java:
package sdp.sy_3.builderpattern;
public class Director {
private SetMealBuilder setMealBuilder;
public Director(SetMealBuilder setMealBuilder) {
this.setMealBuilder = setMealBuilder;
}
public SetMeal construct() {
//准备主食
setMealBuilder.createStapleFood();
//准备饮料
setMealBuilder.createDrinks();
//返回一个套餐
return setMealBuilder.getSetMeal();
}
}
// Client.java:
package sdp.sy_3.builderpattern;
//建造者模式
public class Client {
public static void main(String[] args) {
System.out.println("---------KFC套餐选择---------");
//建造套餐A
SetMealBuilder setMealABuilder = new SetMealBuilderA();
Director kfcDirector = new Director(setMealABuilder);
SetMeal kfcSetMealA = kfcDirector.construct();
System.out.println("套餐A:");
System.out.println("主食:"+kfcSetMealA.getStapleFood()+" 饮料:"+kfcSetMealA.getDringks());
//建造套餐B
SetMealBuilder setMealBBuilder = new SetMealBuilderB();
kfcDirector = new Director(setMealBBuilder);
SetMeal kfcSetMealB = kfcDirector.construct();
System.out.println("套餐B:");
System.out.println("主食:"+kfcSetMealB.getStapleFood()+" 饮料:"+kfcSetMealB.getDringks());
}
}
【运行截图】