应用场景
将各个零件组装起来,比如我们需要组装手机,组装电脑等等。当构建的对象很复杂的时候,需要用到建造者模式。
本质
将子组件的单独构造(由Builder来负责)和装配(由Director负责)进行了分离,这种模式适用于某个对象在构建过程复杂的情况下。由于将构建与装配解耦,不同的构建器,相同的装配也可以产生不同的对象。构建器相同,但装配不同,也可以产生不同的对象。
示例
实体类
实体类表示各个部件具体的类,比如飞船应该有自己的实体类,然后飞船内部有轨道舱、逃逸塔、引擎的实体类。
package com.dy.xidian; public class AirShip { private OrbitalModule orbitalModule; private Engine engine; private EscapeTower escapeTower; public OrbitalModule getOrbitalModule() { return orbitalModule; } public void setOrbitalModule(OrbitalModule orbitalModule) { this.orbitalModule = orbitalModule; } public Engine getEngine() { return engine; } public void setEngine(Engine engine) { this.engine = engine; } public EscapeTower getEscapeTower() { return escapeTower; } public void setEscapeTower(EscapeTower escapeTower) { this.escapeTower = escapeTower; } } class OrbitalModule { private String name; public OrbitalModule(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } class Engine { private String name; public Engine(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } class EscapeTower { private String name; public EscapeTower(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
构建器接口
为了解耦,我们需要为不同构建器定义自己的接口类。
package com.dy.xidian; public interface AirShipBuilder { Engine builerEngine(); OrbitalModule builerOrbitalModule(); EscapeTower builderEscapeTower(); }
构建器类
package com.dy.xidian; public class AirShipBuilderImpl implements AirShipBuilder { @Override public Engine builerEngine() { System.out.println("发动机"); return new Engine("构建发动机"); } @Override public OrbitalModule builerOrbitalModule() { System.out.println("轨道舱"); return new OrbitalModule("构建轨道舱"); } @Override public EscapeTower builderEscapeTower() { System.out.println("逃逸塔"); return new EscapeTower("构建逃逸塔"); } }
装配器接口
装配器通过装配应该返回一个装配好的对象
package com.dy.xidian; public interface AirShipDirector { AirShip directorAirShip(); }
装配器类
package com.dy.xidian; public class AirShipDirectorImpl implements AirShipDirector { private AirShipBuilder builder; public AirShipDirectorImpl(AirShipBuilder builder) { this.builder = builder; } @Override public AirShip directorAirShip() { Engine e = builder.builerEngine(); OrbitalModule o = builder.builerOrbitalModule(); EscapeTower et = builder.builderEscapeTower(); AirShip ship = new AirShip(); ship.setEngine(e); ship.setEscapeTower(et); ship.setOrbitalModule(o); return ship; } }
装配器在装配时首先要通过builder类将各个部件构造出来,然后对其组装。这里的builder可以使用简单工厂模式来生成各个部件。
客户
package com.dy.xidian; public class Clinet { public static void main(String[] args) { AirShipDirector director = new AirShipDirectorImpl( new AirShipBuilderImpl()); AirShip ship = director.directorAirShip(); } }
客户选择一个具体的构建器,让装配器对其进行组装。
应用
StringBuilder类的append方法
JDOM中的DOMBuiler,SAXBuilder方法