标签:
GOF:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
通过建造者模式,用户只需指定需要建造的类型就可以得到它们,而具体的建造过程和细节就不需要知道了。实际上建造者模式就是将创建的流程放到抽象类(或接口)中,将流程中的具体实现放到子类中实现。
例子:比如炒饭,炒饭的流程就是,但是有的客人要求咸一点,有的客人要求蛋多一点,这就导致具体的炒饭会有所不同。因此我们将加饭的量,鸡蛋的量,配料的量,和翻炒时间都放到子类(或实现接口的类)中去实现,而将流程放到抽象类/接口中,通过厨师(Directo)来将饭炒好给客人品尝。
经典类图:
以下以上面的炒饭为例子:
public class 建造者模式 { public static void main(String[] args) { ChaofanDirector cd = new ChaofanDirector(); Chaofan chaofan = cd.constructChaofan(new MoreEggChaofanBuilder()); chaofan.print(); chaofan = cd.constructChaofan(new SaltyChaofanBuilder()); chaofan.print(); } } enum Size { LITTLE, NORMAL, MUCH }; //Product class Chaofan { public Size rice; //这里节省空间就不写getters/setters public Size egg; public Size spices; public Size stirfly; public void print() { System.out.println(rice + " Rice, " + egg + " Egg, " + spices + " Spices, " + stirfly + " Stirfly"); } } //Builder interface ChaofanBuilder { void addRice(); void addEgg(); void addSpices(); void stirFly(); Chaofan buildChaofan(); } //ConcreteBuilder class SaltyChaofanBuilder implements ChaofanBuilder { Chaofan chaofan; public SaltyChaofanBuilder() { chaofan = new Chaofan(); } public void addRice() { chaofan.rice = Size.NORMAL; } public void addEgg() { chaofan.egg = Size.NORMAL; } public void addSpices() { chaofan.spices = Size.MUCH; } public void stirFly() { chaofan.stirfly = Size.NORMAL; } public Chaofan buildChaofan() { return chaofan; } } class MoreEggChaofanBuilder implements ChaofanBuilder { Chaofan chaofan; public MoreEggChaofanBuilder() { chaofan = new Chaofan(); } public void addRice() { chaofan.rice = Size.NORMAL; } public void addEgg() { chaofan.egg = Size.MUCH; } public void addSpices() { chaofan.spices = Size.NORMAL; } public void stirFly() { chaofan.stirfly = Size.NORMAL; } public Chaofan buildChaofan() { return chaofan; } } //Director class ChaofanDirector { public Chaofan constructChaofan(ChaofanBuilder cb) { cb.addRice(); cb.addEgg(); cb.addSpices(); cb.stirFly(); return cb.buildChaofan(); } }
分析:我们要的炒饭就是Chaofan类,即类图中的Product,炒饭的流程都是一样的,该流程放在了Builder即ChaofanBuilder类中,而客人要求的炒饭是不同的,具体的炒饭实现方式放在了ConcreteBuilder即MoreEggChaofanBuilder和SaltyChaofanBuilder中,而Director即ChaofanDirector就是厨师,负责把饭炒好,然后给客人品尝。
总结:将流程放到接口中,具体细节放到子类中,通过Director创建出Product。
标签:
原文地址:http://www.cnblogs.com/programmer-kaima/p/4411077.html