//产品 - Product(产品角色)
public class House {
private String basic;
private String wall;
private String roofed;
public String getBasic() {
return basic;
}
public void setBasic(String basic) {
this.basic = basic;
}
public String getWall() {
return wall;
}
public void setWall(String wall) {
this.wall = wall;
}
public String getRoofed() {
return roofed;
}
public void setRoofed(String roofed) {
this.roofed = roofed;
}
}
2. Builder(抽象建造者)
// Builder(抽象建造者)
public abstract class HouseBuilder {
protected House house = new House();
//将建造的流程写好,抽象方法
//打地基
public abstract void buildBasic();
//砌墙
public abstract void buildWalls();
//封顶
public abstract void roofed();
//建造房子,将产品返回
public House buildHouse(){
return house;
}
}
3. ConcreteBuilder(具体建造者)
普通房子
public class CommonHouse extends HouseBuilder{
@Override
public void buildBasic() {
System.out.println(" 普通房子打地基 5 米");
}
@Override
public void buildWalls() {
System.out.println(" 普通房子砌墙 10米");
}
@Override
public void roofed() {
System.out.println(" 普通房子封顶");
}
}
高楼
public class HighBuilding extends HouseBuilder{
@Override
public void buildBasic() {
System.out.println(" 高楼打地基 100m");
}
@Override
public void buildWalls() {
System.out.println(" 高楼砌墙20cm");
}
@Override
public void roofed() {
System.out.println("高楼的屋顶");
}
}
4. Director(指挥者)
// ConcreteBuilder(具体建造者) 指定具体的制作流程
public class HouseDirecter {
HouseBuilder houseBuilder = null;
//构造器传入
public HouseDirecter(HouseBuilder houseBuilder){
this.houseBuilder = houseBuilder;
}
//通过setter方法
public void setHouseBuilder(HouseBuilder houseBuilder) {
this.houseBuilder = houseBuilder;
}
//如何处理建造房子的流程,交给指挥者
public House constructHouse(){
houseBuilder.buildBasic();
houseBuilder.buildWalls();
houseBuilder.roofed();
return houseBuilder.buildHouse();
}
}
5. 测试类
public class Client {
public static void main(String[] args) {
//盖普通房子
CommonHouse commonHouse = new CommonHouse();
//准备创建房子的指挥者
HouseDirecter houseDirecter = new HouseDirecter(commonHouse);
House house = houseDirecter.constructHouse();
}
}