建造者模式的本质
-分离了对象子组件的单独构造(由Builder来负责)和装配(由Director负责)。从而可以构造出复杂的对象。这个模式适用于:某个对象的构建过程复杂的情况下使用。
-由于实现了构建和装配的解耦。不同的构建器,相同的装配,也可以做出不同的对象;相同的构建器,不同的装配顺序也可以做出不同的对象。也就是实现了构建算法、装配算法 的解耦,实现了更好的复用。
建造者模式实现
飞船类:
package Builder;
/**
* 飞船
* @author ly
*
*/
public class AirShip {
private OrbirtalModule orbitaiModule;//轨道舱模块
private Engine engine;//发动机
private EscapeTower escapeTower;//逃逸舱
public void launch() {
System.out.println("发射!");
}
public OrbirtalModule getOrbitaiModule() {
return orbitaiModule;
}
public void setOrbitaiModule(OrbirtalModule orbitaiModule) {
this.orbitaiModule = orbitaiModule;
}
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 OrbirtalModule {
private String name;
public OrbirtalModule(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 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 Builder;
public interface AirShipBuilder {
Engine builderEngine();
OrbirtalModule builderOrbirtalModule();
EscapeTower builderEscapeTower();
}
飞船装配接口:
package Builder;
public interface AirShipDirector {
/**
* 组装飞船对象
* @return
*/
AirShip createAirShip();
}
飞船构建类:
package Builder;
public class MyAirShipBuilder implements AirShipBuilder{//StringBuilder XML解析中,JDOM库中的类:DomBuilder,SaxBuilder
@Override
public Engine builderEngine() {
System.out.println("构建发动机");
return new Engine("My发动机!");
}
@Override
public OrbirtalModule builderOrbirtalModule() {
System.out.println("构建轨道舱");
return new OrbirtalModule("My轨道舱!");
}
@Override
public EscapeTower builderEscapeTower() {
System.out.println("构建逃逸舱");
return new EscapeTower("My逃逸舱!");
}
}
飞船组装类:
package Builder;
public class MyAirShipDirector implements AirShipDirector{
private AirShipBuilder builder;
public MyAirShipDirector(AirShipBuilder builder) {
this.builder = builder;
}
@Override
public AirShip createAirShip() {
Engine e = builder.builderEngine();
OrbirtalModule om = builder.builderOrbirtalModule();
EscapeTower et = builder.builderEscapeTower();
//装配成飞船对象
AirShip ship = new AirShip();
ship.setEngine(e);
ship.setOrbitaiModule(om);
ship.setEscapeTower(et);
return ship;
}
}
调用者类:
package Builder;
public class Client {
public static void main(String[] args) {
AirShipDirector director = new MyAirShipDirector(new MyAirShipBuilder());
AirShip ship = director.createAirShip();
System.out.println(ship.getEngine().getName());
ship.launch();
}
}