来源:http://www.bjsxt.com/
一、【GOF23设计模式】建造者模式详解类图关系
建造飞船
package com.test.Builder; public class AirShip {
private OrbitalModule orbitalModule;//轨道舱
private Engine engine;//发动机
private EscapeTower escapeTower;//逃逸塔 public void launch(){
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 EscapeTower getEscapeTower() {
return escapeTower;
}
public void setEscapeTower(EscapeTower escapeTower) {
this.escapeTower = escapeTower;
}
} class OrbitalModule{
private String name; public OrbitalModule(String name) {
super();
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) {
super();
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.test.Builder; public interface AirShipBuilder {
OrbitalModule buildOrbitalModule();
Engine builderEngine();
EscapeTower builderEscapeTower();
}
组装接口
package com.test.Builder; public interface AirShipDirector {
/**
* 组装飞船对象
*/
AirShip directAirShip();
}
构造实现类
package com.test.Builder;
/**
* StringBuilder,以后学习XML解析中,JDOM库中的类:DomBuilder,SaxBuilder
*/
public class SxtAirShipBuilder implements AirShipBuilder{ @Override
public OrbitalModule buildOrbitalModule() {
System.out.println("构建sxt轨道舱");
return new OrbitalModule("sxt轨道舱");
} @Override
public Engine builderEngine() {
System.out.println("构建sxt发动机");
return new Engine("sxt发动机");
} @Override
public EscapeTower builderEscapeTower() {
System.out.println("构建sxt逃逸塔");
return new EscapeTower("sxt逃逸塔");
}
}
组装实现类
package com.test.Builder; public class SxtAirShipDirector implements AirShipDirector{ private AirShipBuilder builder; public SxtAirShipDirector(AirShipBuilder builder) {
super();
this.builder = builder;
} @Override
public AirShip directAirShip() {
OrbitalModule o = builder.buildOrbitalModule();
Engine e = builder.builderEngine();
EscapeTower et = builder.builderEscapeTower(); AirShip ship = new AirShip();
ship.setOrbitalModule(o);
ship.setEngine(e);
ship.setEscapeTower(et);
return ship;
}
}
package com.test.Builder; public class Client {
public static void main(String[] args) {
AirShipDirector director = new SxtAirShipDirector(new SxtAirShipBuilder());
AirShip ship = director.directAirShip();
System.out.println(ship.getEngine().getName());
ship.launch();
}
}