设计模式之建造模式

本质

– 分离了对象 子组件的单独构造(由Builder来负责)和装配(由Director负责)。
– 由于实现了构建和装配的解耦。不同的构建器,相同的装配,也可以做出不同的对象; 相同的构建器,不同的装配顺序也可以做出不同的对象。也就是实现了构建算法、装配 算法的解耦,实现了更好的复用。

代码

AirShip.java
package com.bjsxt.builder;
/**
* 宇宙飞船
*/
public class AirShip {
    
    private OrbitalModule orbitalModule;  //轨道舱
    private Engine engine; //发动机
    private EscapeTower escapeTower;  //逃逸塔
    
    public void launch(){
        System.out.println("发射!");
    }
    //get set 方法
}

class OrbitalModule{
    private String name;

    public OrbitalModule(String name) {
        this.name = name;
    }
    //get set 方法
}

class Engine {
    private String name;

    public Engine(String name) {
        this.name = name;
    }
    //get set 方法
}


class EscapeTower{
    private String name;

    public EscapeTower(String name) {
        this.name = name;
    }
    //get set 方法
}


AirShipBuilder.java
public interface AirShipBuilder {
    Engine builderEngine();
    OrbitalModule builderOrbitalModule();
    EscapeTower  builderEscapeTower();
}

AirShipDirector.java
public interface AirShipDirector {
    /**
     * 组装飞船对象
     * @return
     */
    AirShip   directAirShip();
}

SxtAirShipBuilder.java
public class SxtAirShipBuilder implements AirShipBuilder {
    //StringBuilder, 以后学习XML解析中,JDOM库中的类:DomBuilder,SaxBuilder
    @Override
    public Engine builderEngine() {
        System.out.println("构建尚学堂牌发动机!");
        return new Engine("尚学堂牌发动机!");
    }

    @Override
    public EscapeTower builderEscapeTower() {
        System.out.println("构建逃逸塔");
        return new EscapeTower("尚学堂牌逃逸塔");
    }

    @Override
    public OrbitalModule builderOrbitalModule() {
        System.out.println("构建轨道舱");
        return new OrbitalModule("尚学堂牌轨道舱");
    }    
    
}

SxtAirshipDirector.java
public class SxtAirshipDirector implements AirShipDirector {

    private AirShipBuilder builder;

    public SxtAirshipDirector(AirShipBuilder builder) {
        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;
    }
}



Client.java
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();
        
    }
}

你可能感兴趣的:(设计模式)