编程语言
首页 > 编程语言> > JAVA设计模式之建造者模式

JAVA设计模式之建造者模式

作者:互联网

建造者模式

生成器模式,将复杂对象的构建过程抽象出来,不同抽象过程的不同方法可以构造不同属性对象

核心角色

House:产品

@Data
public class House {
    private String basic;
    private String wall;
    private String roof;
}

HouseBuilder:抽象建造者

public abstract class HouseBuilder {
    House house=new House();
    
    public abstract void buildBasic();
    public abstract void buildWall();
    public abstract void buildRoof();
    
    public House buildHouse() {
        return house;
    }
}

CommonBuilder:具体建造者

public class CommonBuilder extends HouseBuilder {
    House house = new House();
    public CommonBuilder() {
        house.setBasic("100m");
        house.setWall("瓷砖");
        house.setRoof("瓦片");
    }

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

    @Override
    public void buildWall() {
        System.out.println("普通房子建墙"+house.getWall());
    }

    @Override
    public void buildRoof() {
        System.out.println("普通房子盖屋顶"+house.getRoof());
    }
}

HouseDirector:指挥者

public class HouseDirector {
    HouseBuilder houseBuilder;
    
    public HouseDirector(HouseBuilder houseBuilder) {
        this.houseBuilder = houseBuilder;
    }
    public void setHouseBuilder(HouseBuilder houseBuilder) {
        this.houseBuilder = houseBuilder;
    }
    //实现构造房子交给指挥者
    public House constructHouse() {
        houseBuilder.buildBasic();
        houseBuilder.buildWall();
        houseBuilder.buildRoof();
        return houseBuilder.buildHouse(); //返回一个House产品对象
    }
}

实现

public class Client {
    public static void main(String[] args) {
        HouseDirector houseDirector1 = new HouseDirector(new CommonBuilder());
        houseDirector1.constructHouse();
    }
}

结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OU49hmMY-1606396889371)(C:\Users\acer\AppData\Roaming\Typora\typora-user-images\image-20201126211205410.png)]

标签:JAVA,house,void,建造,houseBuilder,House,设计模式,public,HouseBuilder
来源: https://blog.csdn.net/zhangxuchuan111/article/details/110205456