建造者模式包括以下几个角色
1.builder 抽象建造者 为要创建的产品对象的各个部件指定抽象接口,声明builderPartX()方法,getResult()方法返回复杂对象方法。
2.concrete Builder 具体建造者 实现builder接口,实现各个部件的构造和装配方法,定义并明确它所创建的对象。
3.product 产品角色 被构建的复杂对象,被具体建造者创建。
4.Director 指挥者 与builder存在关联关系,可以在器construct()建造方法中调用对象的部件构造和装配方法。与客户端交互,示例化具体建造者对象(通过配置文件或反射机制)。通过构造函数或set()方法,将对象传入指挥者。
例子
//产品角色
public class Meal{
private String food;
private String drink;
public void setFood(String food){
this.food=food;
}
public String getFood(){
return (this.food);
}
public void setDrink(String drink){
this.drink=drink;
}
public String getDrink(){
return (this.drink);
}
}
//抽象建造者
public abstract class MealBuilder{
protected Meal meal = new Meal();
public abstract void buildFood();
public abstract void buildDrink();
public Meal getMeal(){
return meal;
}
}
//具体建造者 A
public class SubMealBuilderA extends MealBuilder{
public void buildFood(){
meal.setFood("a hootdog");
}
public void buildDrink(){
meal.setDrink("a cup of coco");
}
}
//具体建造者 B
public class SubMealBuildeB extends MealBuilder{
public void buildFood(){
meal.setFood("beaf");
}
public void buildDrink(){
meal.setDrink("a cup of silk");
}
}
//指挥者类
public class KFCWaiter{
private MealBuilder mb;
public void setMealBuilder(MealBuilder mb){
this.mb=mb;
}
public Meal construct(){
mb.buildFood();
mb.buildDrink();
return mb.getMeal();
}
}
//客户端类
public class ClientBuilder{
public static void main(String[] args) {
MealBuilder mb =new SubMealBuilderB();
KFCWaiter waiter =new KFCWaiter();
waiter.setMealBuilder(mb);
Meal meal = waiter.construct();
System.out.println("----meal----");
System.out.println(meal.getFood());
System.out.println(meal.getDrink());
}
}
结果:
----meal----
beaf
a cup of silk