建造者模式将一个复杂的构建与其表示相分离,是的同样的构建过程可以创建不同的表示。
为了说明建造者模式的设计方法,下面使用一个快餐店的点餐过程作为例子来进行说明。顾客如果要点单个食品,这时软件的实现就可以通过使用简单工厂,但是如果点套餐,那么就比较麻烦,比如一个KFC的套餐。抽象下分为:套餐的组合过程,生成套餐的具体食品。
建造者模式的各种参与者有:Builder,BuilderImplx,Director,具体代码如下:
抽象建造者类:
Builder.javaimport java.util.ArrayList;import java.util.List;abstract public class Builder{ private List productList; public List getProductList(){ return productList; } public void setProductList(){ return productList; } public void init(){ productList=new ArrayLsit(); } public void createFoodA(){ } public void createFoodB(){ } public void createDrink(){ } public void createAddition(){ }
儿童套餐实现类:
BuilderImplA.javapublic class BuilderImplA extends Builder{ public void createFoodA(){ getProductList().add("麦香鱼汉堡"); } public void createFoodB(){ getProductList().add("小薯条"); } public void createDrink(){ getProductList().add("奶昔"); } public void createAddition(){ getProductList().add("喜洋洋玩具"); }
成人套餐实现类:
BuilderImplB.javapublic class BuilderImplB extends Builder{ public void createFoodA(){ getProductList().add("巨无霸汉堡"); } public void createFoodB(){ getProductList().add("大薯条"); } public void createDrink(){ getProductList().add("大杯可乐"); }}
下面展示的是控制建造过程的抽象导演类:
Director.javaimport java.util.List;abstract public class Director{ private Builder builder; public Builder getBuilder(){ return builder; } public void setBuilder(Builder builder){ this.builder=builder; } public Director(Builder builder){ super(); this.builder=builder; } public abstract List construct();}
导演类的实现类:
DirectorImpl.javainport java.util.List;public class DirectorImpl extends Director{ public DirectorImpl(Builder builder){ super(builder); } @Override public List construct(){ getBuilder().init(); getBuilder().createFoodA(); getBuilder().createFoodB(); getBuilder().createDrink(); getBuilder().createAddition(); return getBuilder().geProductList(); }}
客户端代码:
import java.util.List;public class Client{ public static void main(String[] args){ Director director; director =new DirectorImpl(new BuliderImplA()); List aList=director.construct(); Client.viewList(aList); director =new DirectorImpl(new BuliderImplB()); List aList=director.construct(); Client.viewList(aList); } public static void viewList(List list){ for(Object object:list){ System.out.print(object+" "); } System.out.println(); }}
运行结果如下:
麦香鱼汉堡 小薯条 奶昔 喜洋洋玩具
巨无霸汉堡 大薯条 大杯可乐