核心本质:
分离了对象子组件的单独构造(由Builder来负责)和装配(由Director负责)。从而可以构造出复杂的对象。
使用性:
某个对象的构建过程复杂的情况下
特点:
由于实现了构造和装配的解耦。不同的构建器,相同的装配,也可以做出不同的对象;相同的构建器,不同的装配顺序也可以做出不同的对象。也就是实现了构建算法,装配算法的解耦,实现了更好的复用
应用场景:
实现例子代码:
package com.lp.builder; 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; OrbitalModule (String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } class Engine{ private String name; Engine (String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } class EscapeTower{ private String name; EscapeTower (String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
飞船以及可以被装配的构建
package com.lp.builder; public interface AirShipBuilder { Engine builderEngine(); OrbitalModule builderOrbitaModule(); EscapeTower builderEscaperTower(); }
飞船构造接口
package com.lp.builder; //组装飞船 public interface AirShipDirector { AirShip directAirShip(); }
飞船装配接口
package com.lp.builder; public class LpAirShipBuilder implements AirShipBuilder{ @Override public Engine builderEngine() { System.out.println("构建李鹏牌发动机"); return new Engine("李鹏牌发动机"); } @Override public OrbitalModule builderOrbitaModule() { System.out.println("构建李鹏牌轨道舱"); return new OrbitalModule("李鹏牌轨道舱"); } @Override public EscapeTower builderEscaperTower() { System.out.println("构建李鹏牌逃逸舱"); return new EscapeTower("李鹏牌逃逸舱"); } //StringBuildr }
李鹏的飞船构造接口
package com.lp.builder; public class LpAirShipDirector implements AirShipDirector { private AirShipBuilder builder; LpAirShipDirector(AirShipBuilder builder){ this.builder = builder; } @Override public AirShip directAirShip() { Engine e = builder.builderEngine(); OrbitalModule o = builder.builderOrbitaModule(); EscapeTower es = builder.builderEscaperTower(); AirShip ship = new AirShip(); ship.setEngine(e); ship.setEscapeTower(es); ship.setOrbitalModule(o); return ship; } }
李鹏的飞船装配接口
时间: 2024-10-02 00:57:14