1. 定义:
-
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
-
在用户不知道对象的建造过程和细节的情况下,可以直接创建复杂的对象。
2. 优缺点
-
优点:隐藏复杂的实现细节,易于解耦,方便扩展
-
缺点:当产品内部变化复杂,产品间差异较大时,不适合使用建造者模式
3. Android源码中的体现
AlertDialog,Notification的Builder,StringBuilder, StringBuffer 等,这些都是我们日常开发中经常会用到的
4. 实例演示
下面结合一个实例来分析一下建造者模式的原理,以组装手机为例:
- 首先是定义一个手机的基类,包含一些手机的共有属性和方法;
abstract class MobilePhone {
protected String cpu;
protected String ram;
protected String os;
protected MobilePhone() {
}
public abstract void setCPU();
public void setRAM(String ram) {
this.ram = ram;
}
public void setOS(String os) {
this.os = os;
}
@Override
public String toString() {
return "MobilePhone{" +
"cpu='" + cpu + '\'' +
", ram=" + ram +
", os='" + os + '\'' +
'}';
}
}
- 创建具体的实现类,如华为手机,实现了基类的抽象方法,并扩展增加了AI智能芯片
class HuaWeiPhone extends MobilePhone {
protected String aiCpu;
protected HuaWeiPhone() {
}
@Override
public void setCPU() {
this.cpu = "麒麟970";
}
public void setAiCpu(String aiCpu) {
this.aiCpu = aiCpu;
}
@Override
public String toString() {
return "HuaWeiPhone{" +
"cpu='" + cpu + '\'' +
", ram=" + ram +
", os='" + os + '\'' +
", aiCpu='" + aiCpu + '\'' +
'}';
}
}
- 创建一个建造者的基类,通过范型控制要构造的实例类型
abstract class PhoneBuilder <T extends MobilePhone> {
protected T phone
public abstract void buildRAM(int ram);
public abstract void buildOS(String os);
public abstract T build();
}
- 创建华为手机的建造者
class HuaWeiBuilder extends PhoneBuilder {
HuaWeiParam mHuaWeiParam;
private HuaWeiPhone huaWeiPhone;
public HuaWeiBuilder() {
mHuaWeiParam = new HuaWeiParam();
}
public HuaWeiBuilder buildAICPU(boolean isSupportAi) {
if (isSupportAi) {
mHuaWeiParam.aiCpu = "麒麟AI芯片";
}
return this;
}
@Override
public HuaWeiBuilder buildRAM(int ram) {
mHuaWeiParam.ram = String.format("AMD-007 %dG", ram);
return this;
}
@Override
public HuaWeiBuilder buildOS(String os) {
mHuaWeiParam.os = os;
return this;
}
@Override
public HuaWeiPhone build() {
huaWeiPhone = new HuaWeiPhone();
huaWeiPhone.setCPU();
huaWeiPhone.setOS(mHuaWeiParam.os);
huaWeiPhone.setRAM(mHuaWeiParam.ram);
huaWeiPhone.setAiCpu(mHuaWeiParam.aiCpu);
return huaWeiPhone;
}
class HuaWeiParam {
String aiCpu;
String os;
String ram;
}
}
- 使用Builder构建手机实例,如下程序,构造不同型号的华为手机就非常方便了
private void methodBuilderPattern() {
HuaWeiPhone huaWeiP20=new HuaWeiBuilder()
.buildOS("android 9.0")
.buildRAM(6)
.buildAICPU(false)
.build();
HuaWeiPhone huaWeiMate40=new HuaWeiBuilder()
.buildOS("Harmony 1.0")
.buildRAM(8)
.buildAICPU(true)
.build();
}
网友评论