1public class Building {// 建筑物 2 3 // 用来模拟房子组件的堆叠 4 private List<String> buildingComponents = new ArrayList<>(); 5 6 public void setBasement(String basement) {// 地基 7 this.buildingComponents.add(basement); 8 } 9 10 public void setWall(String wall) {// 墙体 11 this.buildingComponents.add(wall); 12 } 13 14 public void setRoof(String roof) {// 房顶 15 this.buildingComponents.add(roof); 16 } 17 18 @Override 19 public String toString() { 20 String buildingStr = ""; 21 for (int i = buildingComponents.size() - 1; i >= 0; i--) { 22 buildingStr = buildingComponents.get(i); 23 } 24 return buildingStr; 25 } 26 27}
1public interface Builder {//施工方接口 2 3 public void buildBasement(); 4 5 public void buildWall(); 6 7 public void buildRoof(); 8 9 public Building getBuilding(); 10 11}
1public class HouseBuilder implements Builder {//别墅施工方 2 3 private Building house; 4 5 public HouseBuilder() { 6 house = new Building(); 7 } 8 9 @Override 10 public void buildBasement() { 11 System.out.println("挖地基,部署管道、线缆,水泥加固,搭建围墙、花园。"); 12 house.setBasement("╬╬╬╬╬╬╬╬\n"); 13 } 14 15 @Override 16 public void buildWall() { 17 System.out.println("搭建木质框架,石膏板封墙并粉饰内外墙。"); 18 house.setWall("|田|田 田|\n"); 19 } 20 21 @Override 22 public void buildRoof() { 23 System.out.println("建造木质屋顶、阁楼,安装烟囱,做好防水。"); 24 house.setRoof("╱◥███◣\n"); 25 } 26 27 @Override 28 public Building getBuilding() { 29 return house; 30 } 31 32}
1public class ApartmentBuilder implements Builder {// 高层公寓楼施工方 2 3 private Building apartment; 4 5 public ApartmentBuilder() { 6 apartment = new Building(); 7 } 8 9 @Override 10 public void buildBasement() { 11 System.out.println("深挖地基,修建地下车库,部署管道、线缆、风道。"); 12 apartment.setBasement("╚═════════╝\n"); 13 } 14 15 @Override 16 public void buildWall() { 17 System.out.println("搭建多层建筑框架,建造电梯井,钢筋混凝土浇灌。"); 18 for (int i = 0; i < 8; i ) {// 此处假设固定8层 19 apartment.setWall("║ □ □ □ □ ║\n"); 20 } 21 } 22 23 @Override 24 public void buildRoof() { 25 System.out.println("封顶,部署通风井,做防水层,保温层。"); 26 apartment.setRoof("╔═════════╗\n"); 27 } 28 29 @Override 30 public Building getBuilding() { 31 return apartment; 32 } 33 34}
1public class Director {//工程总监 2 3 private Builder builder; 4 5 public Director(Builder builder) { 6 this.builder = builder; 7 } 8 9 public void setBuilder(Builder builder) { 10 this.builder = builder; 11 } 12 13 public Building direct() { 14 System.out.println("=====工程项目启动====="); 15 // 第一步,打好地基; 16 builder.buildBasement(); 17 // 第二步,建造框架、墙体; 18 builder.buildWall(); 19 // 第三步,封顶; 20 builder.buildRoof(); 21 System.out.println("=====工程项目竣工====="); 22 return builder.getBuilding(); 23 } 24 25}