设计模式四:建造者模式

应用场景: 

   如果开发中我们需要构建复杂对象(属性很多 装配比较麻烦) 一般使用建造者模式

本质:

    实现了组件的构造(builder)和装配(Director)的分离

不同的构建相同的组装那么产生的对象时不同的

public class AirShip {
    private Engine engine;//发动机

    private Escape escape;//逃离器

    public Engine getEngine() {
        return engine;
    }

    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    public Escape getEscape() {
        return escape;
    }

    public void setEscape(Escape escape) {
        this.escape = escape;
    }
}

class Engine {
    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

class Escape {
    private String desc;

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}

构造者

interface IAirShipBuilder {
    Engine buildEngine();
    Escape buildEscape();
}
public class MyAirShipBuilder implements IAirShipBuilder {
    @Override
    public Engine buildEngine() {
        Engine engine = new Engine();
        engine.setType("最好的");
        return engine;
    }

    @Override
    public Escape buildEscape() {
        Escape escape = new Escape();
        escape.setDesc("也是最好的");
        return escape;
    }
}


装配者

interface IAirShipDirector {
    AirShip buildAirShip();
}
public class MyAirShipDirector implements IAirShipDirector {

    private IAirShipBuilder airShipBuilder;

    public MyAirShipDirector(IAirShipBuilder airShipBuilder) {
        this.airShipBuilder = airShipBuilder;
    }

    @Override
    public AirShip buildAirShip() {
        AirShip airShip = new AirShip();
        airShip.setEngine(airShipBuilder.buildEngine());
        airShip.setEscape(airShipBuilder.buildEscape());
        return airShip;
    }
}

ok 建造者模式 基本上的demo 就是这样


猜你喜欢

转载自blog.csdn.net/youth_never_go_away/article/details/80743372