构建者模式应用场景:
主要用来构建一些复杂对象,这里的复杂对象比如说:在建造大楼时,需要先打牢地基,搭建框架,然后自下向上地一层一层盖起来。通常,在建造这种复杂结构的物体时,很难一气呵成。我们需要首先建造这个物体的各个部分,然后分阶段将他们组合起来。那么现在就出现了构建者模式:构建者模式由Builder(建造者)和Director(指挥者)组成。请看如下的UML图:
Director类
package com.yuan.builder.demo1;
//指挥:核心,负责指挥构建一个工程,工程如何构建,由它决定 public class Director {
//指挥工人给出执行顺序 public Product build(Builder builder) { builder.buildA(); builder.buildC(); builder.buildD(); builder.buildB(); return builder.getProduct(); }
}
Builder类
package com.yuan.builder.demo1; //抽象的建造者 public abstract class Builder {
abstract void buildA();//地基 abstract void buildB();//钢筋工程 abstract void buildC();//铺电线 abstract void buildD();//粉刷
//完工:得到了具体的产品 abstract Product getProduct(); }
Worker类
package com.yuan.builder.demo1;
/** * 具体的建造者:工人 */ public class Worker extends Builder { private Product product;
public Worker() { this.product = new Product(); }
@Override void buildA() { product.setBuildA("地基"); System.out.println("地基"); }
@Override void buildB() { product.setBuildB("钢筋工程"); System.out.println("钢筋工程"); }
@Override void buildC() { product.setBuildC("铺电线"); System.out.println("铺电线"); }
@Override void buildD() { product.setBuildD("粉刷"); System.out.println("粉刷"); }
@Override Product getProduct() { return product; } }
Product类
package com.yuan.builder.demo1; //产品:房子 public class Product {
private String buildA; private String buildB; private String buildC; private String buildD;
public String getBuildA() { return buildA; }
public void setBuildA(String buildA) { this.buildA = buildA; }
public String getBuildB() { return buildB; }
public void setBuildB(String buildB) { this.buildB = buildB; }
public String getBuildC() { return buildC; }
public void setBuildC(String buildC) { this.buildC = buildC; }
public String getBuildD() { return buildD; }
public void setBuildD(String buildD) { this.buildD = buildD; }
@Override public String toString() { return "Product{" + "buildA='" + buildA + '\'' + ", buildB='" + buildB + '\'' + ", buildC='" + buildC + '\'' + ", buildD='" + buildD + '\'' + '}'; } }
Test类
package com.yuan.builder.demo1;
public class Test { public static void main(String[] args) { //指挥 Director director = new Director(); //指挥具体的工人完成 Product product = director.build(new Worker()); System.out.println(product.toString()); } }
|
拓展思路:
谁知道什么:在面向对象编程中,“谁知道什么”是非常重要的。也就是说,我们需要在编程时注意哪个类可以适用哪些方法以及使用哪个方法到底好不好。
设计时能够决定的事情和不能决定的事情:Builder类中的抽象方法的定义!!!