设计模式--构建者设计模式
1. 概念理解
- 建造者模式,将一个复杂的对象的构建与他的表示分离,使得同样的构建过程可以创建不同的表示;对于大多数的用户来说,并不需要知道构建的过程以及细节,可以通过构建者模式进行设计和描述,建造者模式可以将部件和组装过程分开,一步步的创建一个复杂的对象;
- 构建的过程当中每一个部件就像对象的中的某一个属性一样,建造产品就如同构建对象一样的;
2. 组成
- 有四部分组成:
- product:具体的产品模块,也就是我们最后要构建对象
- Builder接口或者抽象类:规范产品的组件,一般是有子类来实现具体的组成对象的过程;
- ConcreateBuilder:具体的Builder类
- Director类:统一组装过程,需要注意的是在平时的开发中这个一般都会被省略,而是直接使用Bulder来进行对象的构建,这样就会形成流线式的调用;
3. 优缺点
-
优点:
- 将复杂对象的创建封装起来,客户端并不需要知道内部的组成细节
- 产品实现可以被替换,因为客户端只需要看到一个抽象的接口
- 创建者独立,容易扩展;
-
缺点:
- 会产生多余的 Builder 对象以及 Director 对象,消耗内存;
- 与工厂模式相比,采用 Builder 模式创建对象的客户,需要具备更多的领域知识。
4. 代码组成
计算机有很多部分组成,所以构建一个电脑对象:
public class Computer {
private String CPU;
private String GPU;
private String memoryType;
private int memorySize;
private String storageType;
private int storageSize;
private String screenType;
private float screenSize;
private String OSType;
public static class Builder{
private String CPU="core-i7";
private String GPU="mali-4000";
private String memoryType="ddr3 1666MHz";
private int memorySize=8;
private String storageType="hdd";
private int storageSize=500;
private String screenType="IPS";
private float screenSize=27.0f;
private String OSType="win 10";
public Builder(){}
public Builder setCPU(String CPU) {
this.CPU = CPU;
return this;
}
public Builder setGPU(String GPU) {
this.GPU = GPU;
return this;
}
public Builder setMemoryType(String memoryType) {
this.memoryType = memoryType;
return this;
}
public Builder setMemorySize(int memorySize) {
this.memorySize = memorySize;
return this;
}
public Builder setStorageType(String storageType) {
this.storageType = storageType;
return this;
}
public Builder setStorageSize(int storageSize) {
this.storageSize = storageSize;
return this;
}
public Builder setScreenType(String screenType) {
this.screenType = screenType;
return this;
}
public Builder setScreenSize(float screenSize) {
this.screenSize = screenSize;
return this;
}
public Builder setOSType(String OSType) {
this.OSType = OSType;
return this;
}
public Computer build(){
return new Computer(this);
}
}
public Computer(Builder builder) {
this.CPU = builder.CPU;
this.GPU = builder.CPU;
this.memoryType = builder.memoryType;
this.memorySize = builder.memorySize;
this.storageType = builder.storageType;
this.storageSize = builder.storageSize;
this.screenType = builder.screenType;
this.screenSize = builder.screenSize;
this.OSType = builder.OSType;
}