建造者模式
生成器模式,将复杂对象的构建过程抽象出来,不同抽象过程的不同方法可以构造不同属性对象
核心角色
-
Product(产品角色):一个具体产品
-
Builder(抽象建造者):创建一个product对象的各个部件的接口/抽象类
-
ConcreteBuilder(具体建造者):实现接口,构造部件
-
Director(指挥者):构建一个使用Builder接口的对象。它主要是用于创建一个复杂的对象。它主要有两个作用,一是:隔离了客户与对象的生产过程,二是:负责控制产品对象的生产过程。
实例
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();
}
}
结果