建造模式是将复杂的内部创建封装在内部,对于外部调用的人来说,只需要传入建造者和建造工具,对于内部是如何建造成成品的,调用者无需关心。
举个例子:汽车的生产
/** * 构建汽车 * @author Administrator * */ public class Car { //企业发动机 private Fadongji fadongji; //模型 private Moju moju; /** * 运行汽车 */ public void run(){ System.out.println("运行汽车"); } public Fadongji getFadongji() { return fadongji; } public void setFadongji(Fadongji fadongji) { this.fadongji = fadongji; } public Moju getMoju() { return moju; } public void setMoju(Moju moju) { this.moju = moju; } } /** * 发动机类 * @author Administrator * */ class Fadongji{ String name; public Fadongji(String name) { super(); this.name = name; } } //模具 class Moju{ String name; public Moju(String name) { super(); this.name = name; } }
建造者
/** * 建造 * @author Administrator * */ public interface CarBuilderInstance { Fadongji buildFadongji(); Moju buildMoju(); }
装备者
/** * 装配 * @author Administrator * */ public interface CarDirectorInstance { Car directorCar(); }
建造者的具体实现
/** * 一汽厂商 * @author Administrator * */ public class YiqiBuilder implements CarBuilderInstance { public Fadongji buildFadongji() { System.out.println("一汽发动机"); return new Fadongji("一汽发动机"); } public Moju buildMoju() { System.out.println("一汽模具"); return new Moju("一汽模具"); } }
装配者的具体实现
/** * 一汽装配 * @author Administrator * */ public class YiqiDirector implements CarDirectorInstance{ //需要建造者进行装配 private CarBuilderInstance builder; public YiqiDirector(CarBuilderInstance builder) { super(); this.builder = builder; } public Car directorCar() { Fadongji fadongji = builder.buildFadongji(); Moju moju = builder.buildMoju(); Car car = new Car(); car.setFadongji(fadongji); car.setMoju(moju); return car; } }
测试
public class Client { public static void main(String[] args) { CarDirectorInstance directorInstance = new YiqiDirector(new YiqiBuilder()); Car car = directorInstance.directorCar(); car.run(); } }
需要现有建造再有装配
应用例子:StringBuilder中append, PreparedStatement