以宇宙飞船为例
package com.imust.builder;
/**
* 宇宙飞船 (实例建造者模式)
* @author Zachary (为上帝所心仪的人)
* @date 2017年9月6日
* @project shejimoshi
* @package com.imust.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 String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public OrbitalModule(String name) {
super();
this.name = name;
}
}
class Engine{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Engine(String name) {
super();
this.name = name;
}
}
class EscapeTower{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EscapeTower(String name) {
super();
this.name = name;
}
}
AirshipBuilder接口类
package com.imust.builder;
public interface AirShipBuilder {
Engine builderEngine();
OrbitalModule builderOrbitalModule();
EscapeTower builderEscapeTower();
}
AirshipDirect(装配类)
package com.imust.builder;
public interface AirShipDirector {
AirShip directAirShip();
}
airShipBuilder实现类
package com.imust.builder;
public class SxtAirShipBuilder implements AirShipBuilder{
@Override
public Engine builderEngine() {
System.out.println("构建发动机");
return new Engine("zzf的发动机");
}
@Override
public OrbitalModule builderOrbitalModule() {
System.out.println("构造轨道舱");
return new OrbitalModule("zzf轨道舱");
}
@Override
public EscapeTower builderEscapeTower() {
System.out.println("构建逃逸塔");
return new EscapeTower("zzf逃逸塔");
}//StringBuilder,DomBuilder
}
airDirector实现类
package com.imust.builder;
public class SxtAirshipDirector implements AirShipDirector {
//构建者
private AirShipBuilder builder;
public SxtAirshipDirector(AirShipBuilder builder) {
super();
this.builder = builder;
}
@Override
public AirShip directAirShip() {
Engine e = builder.builderEngine();
OrbitalModule o = builder.builderOrbitalModule();
EscapeTower et = builder.builderEscapeTower();
//装配成飞船对象
AirShip ship = new AirShip();
ship.setEngine(e);
ship.setEscapeTower(et);
ship.setOrbitalModule(o);
return ship;
}
}
测试类
package com.imust.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();
}
}