2018-04-11
建造者模式
建造者模式是一步一步创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。
包含角色:抽象建造者,具体建造者,指挥者,抽象产品,具体产品
public abstract class Builder {
// 设置CPU核心数
public abstract void buildCPU(int core);
// 设置内存
public abstract void buildRAM(int gb);
// 设置操作系统
public abstract void buildOs(String os);
// 创建Computer
public abstract Computer create();
}
public class ApplePCBuilder extends Builder {
private Computer mComputer = new AppleComputer();
@Override
public void buildCPU(int core) {
mComputer.setCPU(core);
}
@Override
public void buildRAM(int gb) {
mComputer.setRAM(gb);
}
@Override
public void buildOs(String os) {
mComputer.setOs(os);
}
@Override
public Computer create() {
return mComputer;
}
}
public abstract class Computer {
protected int mCpuCore = 1;
protected int mRamSize = 0;
protected String mOperationSystem = "Dos";
// 设置CPU核心数
public abstract void setCPU(int core);
// 设置内存
public abstract void setRAM(int gb);
// 设置操作系统
public abstract void setOs(String os);
@Override
public String toString() {
return "Computer{" +
"mCpuCore=" + mCpuCore +
", mRamSize=" + mRamSize +
", mOperationSystem='" + mOperationSystem + '\'' +
'}';
}
}
public class AppleComputer extends Computer {
@Override
public void setCPU(int core) {
mCpuCore = core;
}
@Override
public void setRAM(int gb) {
mRamSize = gb;
}
@Override
public void setOs(String os) {
mOperationSystem = os;
}
}
public class Director {
public Builder mBuilder = null;
public Director(Builder builder) {
mBuilder = builder;
}
public void construct(int cpu, int ram, String os) {
mBuilder.buildCPU(cpu);
mBuilder.buildRAM(ram);
mBuilder.buildOs(os);
}
}
public class MyClass {
public static void main(String[] args) {
Builder builder = new ApplePCBuilder();
Director director =new Director(builder);
director.construct(4,8,"Window7");
System.out.println(builder.create().toString());
}
}
建造者模式的结构中还引入了一个指挥者类Director,该类的作用主要有两个:一方面它隔离了客户与生产过程;另一方面它负责控制产品的生成过程。指挥者针对抽象建造者编程,客户端只需要知道具体建造者的类型,即可通过指挥者类调用建造者的相关方法,返回一个完整的产品对象;
优缺点
与工厂模式的差异