一、类图
二、实例代码 - KFC套餐
- 1/4_Product
package design.pattern.create.builder.kfc;
public class Meal {
private String food;
private String drink;
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getDrink() {
return drink;
}
public void setDrink(String drink) {
this.drink = drink;
}
}
- 2/4_Builder
package design.pattern.create.builder.kfc;
public abstract class MealBuilder {
protected Meal meal = new Meal();
public abstract void buildFood();
public abstract void buildDrink();
public Meal getMeal() {
return meal;
}
}
- 3/4_ConcreteBuilder
package design.pattern.create.builder.kfc;
public class SubMealBuilderA extends MealBuilder {
@Override
public void buildFood() {
meal.setFood("一个鸡堡");
}
@Override
public void buildDrink() {
meal.setDrink("一杯可乐");
}
}
package design.pattern.create.builder.kfc;
public class SubMealBuilderB extends MealBuilder {
@Override
public void buildFood() {
meal.setFood("一个鸡肉卷");
}
@Override
public void buildDrink() {
meal.setDrink("一杯果汁");
}
}
- 4/4_Director
package design.pattern.create.builder.kfc;
public class KFCWaiter {
private MealBuilder mealBuilder;
public void setMealBuilder(MealBuilder mealBuilder) {
this.mealBuilder = mealBuilder;
}
public Meal construct() {
mealBuilder.buildFood();
mealBuilder.buildDrink();
return mealBuilder.getMeal();
}
}
- 配置文件
<?xml version = "1.0"?>
<config>
<classPath>design.pattern.create.builder.kfc.</classPath>
<className>SubMealBuilderB</className>
</config>
- Client
package design.pattern.create.builder.kfc;
import design.pattern.util.XmlUtil;
public class Client {
public static void main(String[] args) {
String CONFIG_FILE = "design/pattern/create/builder/kfc/z_config.xml";
try {
MealBuilder mb = (MealBuilder)XmlUtil.getBean(CONFIG_FILE);
KFCWaiter waiter = new KFCWaiter();
waiter.setMealBuilder(mb);
Meal meal = waiter.construct();
System.out.println("套餐组成:");
System.out.println(meal.getFood());
System.out.println(meal.getDrink());
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出
套餐组成:
一个鸡肉卷
一杯果汁