一、用建造者解决盖房需求
需要建房子:这一过程为打桩、 砌墙、封顶。不管是普通房子也好,别墅也好都需要经历这些过程, 下面我们使用建造者模式(Builder Pattern)来完成;
UML 类图:
二、代码实现
产品类:
1 /**
2 * 产品 ——》Product
3 */
4 public class House {
5
6 private String basic;
7 private String wall;
8 private String roofed;
9
10 public String getBasic() {
11 return basic;
12 }
13
14 public void setBasic(String basic) {
15 this.basic = basic;
16 }
17
18 public String getWall() {
19 return wall;
20 }
21
22 public void setWall(String wall) {
23 this.wall = wall;
24 }
25
26 public String getRoofed() {
27 return roofed;
28 }
29
30 public void setRoofed(String roofed) {
31 this.roofed = roofed;
32 }
33 }
抽象建造者:
1 /**
2 * 抽象的建造者 ——》Builder
3 */
4 public abstract class HouseBuilder {
5
6 protected House house = new House();
7
8 //将建造的流程写好,抽象的方法
9 public abstract void buildBasic();
10 public abstract void buildWalls();
11 public abstract void roofed();
12
13 /**
14 * 建造房子好, 将产品(房子) 返回
15 */
16 public House buildHouse() {
17 return house;
18 }
19 }
具体建造者:
1 /**
2 * ConcreteBuilder 具体建造者
3 */
4 public class CommonHouse extends HouseBuilder {
5 @Override
6 public void buildBasic() {
7 System.out.println(" 普通房子打地基5米 ");
8 }
9
10 @Override
11 public void buildWalls() {
12 System.out.println(" 普通房子砌墙10cm ");
13 }
14
15 @Override
16 public void roofed() {
17 System.out.println(" 普通房子屋顶 ");
18 }
19 }
20 ---------------------------------------------------
21 /**
22 * ConcreteBuilder 具体建造者
23 */
24 public class HighBuilding extends HouseBuilder {
25 @Override
26 public void buildBasic() {
27 System.out.println(" 高楼的打地基100米 ");
28 }
29
30 @Override
31 public void buildWalls() {
32 System.out.println(" 高楼的砌墙20cm ");
33 }
34
35 @Override
36 public void roofed() {
37 System.out.println(" 高楼的透明屋顶 ");
38 }
39 }
指挥者:
1 /**
2 * Director
3 * 指挥者,这里去指定制作流程,返回产品
4 */
5 public class HouseDirector {
6
7 HouseBuilder houseBuilder = null; //聚合方式
8
9 /**
10 * 构造器传入 houseBuilder
11 * @param houseBuilder
12 */
13 public HouseDirector(HouseBuilder houseBuilder) {
14 this.houseBuilder = houseBuilder;
15 }
16
17 /**
18 * 通过setter 传入 houseBuilder
19 */
20 public void setHouseBuilder(HouseBuilder houseBuilder) {
21 this.houseBuilder = houseBuilder;
22 }
23
24 /**
25 * 如何处理建造房子的流程,交给指挥者
26 * @return
27 */
28 public House constructHouse() {
29 houseBuilder.buildBasic();
30 houseBuilder.buildWalls();
31 houseBuilder.roofed();
32 return houseBuilder.buildHouse();
33 }
34 }
测试代码:
1 /**
2 * 客户端
3 */
4 public class Client {
5 public static void main(String[] args) {
6
7 //盖普通房子
8 CommonHouse commonHouse = new CommonHouse();
9 //准备创建房子的指挥者
10 HouseDirector houseDirector = new HouseDirector(commonHouse);
11
12 //完成盖房子,返回产品(普通房子)
13 House house = houseDirector.constructHouse();
14
15 System.out.println("--------------------------");
16 //盖高楼
17 HighBuilding highBuilding = new HighBuilding();
18 //重置建造者
19 houseDirector.setHouseBuilder(highBuilding);
20 //完成盖房子,返回产品(高楼)
21 houseDirector.constructHouse();
22 }
23 }