设计模式(五)Builder Pattern建造者模式
在我们日常生活中,如构建一个飞船,一个手机,一栋建筑,都会有非常复杂的组装,这时候应该用到建造者模式
以建造一个飞船为例
案例:造小页飞船
1.飞船各部分元件
package com.littlepage.BuilderPattern; public interface AirShipBuilder { Engine builderEngine(); OrbitalModule builderOrbitalModule(); Escape builderEscape(); }
2.飞船实体用来组装
package com.littlepage.BuilderPattern; public class AirShip { private OrbitalModule orbitalModule; private Engine engine; private Escape escape; public void lauch(){ System.out.println("发射"); } 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 Escape getEscape() { return escape; } public void setEscape(Escape escape) { this.escape = escape; } } 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 Escape{ private String name; public Escape(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3.创造方法的接口
package com.littlepage.BuilderPattern; /* *组装飞船对象 */ public interface AirShipDirector { AirShip createAirship(); }
4.实现组件(小页飞船组件)
package com.littlepage.BuilderPattern; public class LittlePageShipBuilder implements AirShipBuilder{ @Override public Engine builderEngine() { System.out.println("页牌发动机"); return new Engine("页牌发动机"); } @Override public OrbitalModule builderOrbitalModule() { System.out.println("页牌逃逸塔"); return new OrbitalModule("页牌逃逸塔"); } @Override public Escape builderEscape() { System.out.println("页牌轨道舱"); return new Escape("页牌轨道舱"); } }
5.实体实现装配
package com.littlepage.BuilderPattern; public class LittlePageAirshipDirector implements AirShipDirector{ private AirShipBuilder builder; public LittlePageAirshipDirector(AirShipBuilder builder) { this.builder = builder; } @Override public AirShip createAirship() { Engine e=builder.builderEngine(); OrbitalModule om=builder.builderOrbitalModule(); Escape et=builder.builderEscape(); AirShip ship=new AirShip(); ship.setEngine(e); ship.setOrbitalModule(om); ship.setEscape(et); return ship; } }
6.客户端的串接(测试)
package com.littlepage.BuilderPattern; public class Client { public static void main(String[] args) { AirShipDirector dir=new LittlePageAirshipDirector(new LittlePageShipBuilder()); AirShip air=dir.createAirship(); System.out.println(air.getEngine()); air.lauch(); } }
UML结构图