建造者模式适用于需要生成的产品对象有复杂的内部结构。
1 //产品2 public class AirShip {3 private Engine engine; //发动机4 private Cabin cabin; //机舱5 private Excape excape; //逃生舱6 public Engine getEngine() {7 return engine;8 }9 public void setEngine(Engine engine) { 10 this.engine = engine; 11 } 12 public Cabin getCabin() { 13 return cabin; 14 } 15 public void setCabin(Cabin cabin) { 16 this.cabin = cabin; 17 } 18 public Excape getExcape() { 19 return excape; 20 } 21 public void setExcape(Excape excape) { 22 this.excape = excape; 23 } 24 } 25 class Engine{ 26 String name; 27 } 28 class Cabin{ 29 String name; 30 } 31 class Excape{ 32 String name; 33 }
1 //产品建造 2 public interface AirShipBuilder { 3 Engine createEngine(); 4 Cabin createCabin(); 5 Excape createExcape(); 6 }
1 //指挥者 2 public interface Director { 3 AirShip createAirship(); 4 }
1 //具体的指挥者2 public class SxtDirector implements Director{3 AirShipBuilder builder;4 //根据不同的建造者5 public SxtDirector(AirShipBuilder builder) {6 this.builder = builder;7 }8 //相同的安装顺序9 @Override 10 public AirShip createAirship() { 11 AirShip ship = new AirShip(); 12 ship.setCabin(builder.createCabin()); 13 ship.setEngine(builder.createEngine()); 14 ship.setExcape(builder.createExcape()); 15 return ship; 16 } 17 }
//具体的建造者 public class SxtAirShipBuilder implements AirShipBuilder{@Overridepublic Engine createEngine() {System.out.println("engine is building");return new Engine();}@Overridepublic Cabin createCabin() {System.out.println("cabin is building");return new Cabin();}@Overridepublic Excape createExcape() {System.out.println("excape is building");return new Excape();} }
1 //用户只需要与指挥者和建造者打交道就可以得到结构复杂的产品 2 public class BuilderDemo { 3 public static void main(String[] args) { 4 AirShipBuilder bu = new SxtAirShipBuilder(); 5 AirShip ship = new SxtDirector(bu).createAirship(); 6 } 7 }