Java设计模式(建造者模式)

package com.jxufe;

import lombok.Data;

@Data
public class House {

    private String base;
    private String walls;
    private String roofed;
}

package com.jxufe;

//抽象的建造者
public abstract class HouseBuilder {
    House house = new House();

    //将建造的流程写好,抽象的方法
    public abstract void buildBasic();
    public abstract void buildWalls();
    public abstract void buildRoofed();

    //建造好房子,将房子返回
    public House buildHouse() {
        return house;
    }

}

package com.jxufe;

public class CommonHouse extends HouseBuilder {

    public void buildBasic() {
        house.setBase("普通地基");
        System.out.println("普通房子打地基");
    }

    public void buildWalls() {
        house.setWalls("普通围墙");
        System.out.println("普通房子砌围墙");
    }

    public void buildRoofed() {
        house.setRoofed("普通屋顶");
        System.out.println("普通房子建屋顶");
    }
}

package com.jxufe;

public class HighHouse extends HouseBuilder {

    public void buildBasic() {
        house.setBase("高楼地基");
        System.out.println("高楼打地基");
    }

    public void buildWalls() {
        house.setWalls("高楼围墙");
        System.out.println("高楼建围墙");
    }

    public void buildRoofed() {
        house.setRoofed("高楼房顶");
        System.out.println("高楼盖房顶");
    }
}

package com.jxufe;

//指挥者,这里去指定制作流程,返回产品
public class HouseDirector {

    HouseBuilder houseBuilder = null;

    //构造器传入houseBuilder
    public HouseDirector(HouseBuilder houseBuilder) {
        this.houseBuilder = houseBuilder;
    }

    //通过setter传入houseBuilder
    public void setHouseBuilder(HouseBuilder houseBuilder) {
        this.houseBuilder = houseBuilder;
    }

    //如何处理建造房子的流程,交给指挥者
    public House constructHouse() {
        houseBuilder.buildBasic();
        houseBuilder.buildWalls();
        houseBuilder.buildRoofed();
        return houseBuilder.buildHouse();
    }
}

package com.jxufe;

public class Client {

    public static void main(String[] args) {
        //盖普通房子
        CommonHouse commonHouse = new CommonHouse();
        //准备创建房子的指挥者
        HouseDirector houseDirector = new HouseDirector(commonHouse);
        //完成盖房子,返回产品
        House house = houseDirector.constructHouse();
        System.out.println(house.toString());

        System.out.println("==================================");

        //盖高楼
        HighHouse highHouse = new HighHouse();
        houseDirector.setHouseBuilder(highHouse);
        house = houseDirector.constructHouse();
        System.out.println(house.toString());
    }
}

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页