您的位置:首页 > 产品设计 > UI/UE

设计模式之Builder模式

2016-07-15 17:49 323 查看

下面是简单的应用场景:组装电脑

Computer类

public class Computer {
private String cpu; // cpu
private String graphicsCard; // 显卡
private String motherBoard; // 主板
private String memory; // 内存
private String hardDsik; // 硬盘
private String display; // 显示器

// 打印验证
@Override
public String toString() {
return "Computer [cpu=" + cpu + ", graphicsCard=" + graphicsCard
+ ", motherBoard=" + motherBoard + ", memory=" + memory
+ ", hardDsik=" + hardDsik + ", display=" + display + "]";
}

public static class Builder {
// 默认值
private String cpu = "i5"; // cpu
private String graphicsCard = "N卡"; // 显卡
private String motherBoard = "技嘉"; // 主板
private String memory = "8G"; // 内存
private String hardDsik = "128G"; // 硬盘
private String display = "华硕"; // 显示器
public Builder setCpu(String cpu) {
this.cpu = cpu;
return this;
}
public Builder setGraphicsCard(String graphicsCard) {
this.graphicsCard = graphicsCard;
return this;
}
public Builder setMotherBoard(String motherBoard) {
this.motherBoard = motherBoard;
return this;
}
public Builder setMemory(String memory) {
this.memory = memory;
return this;
}
public Builder setHardDsik(String hardDsik) {
this.hardDsik = hardDsik;
return this;
}
public Builder setDisplay(String display) {
this.display = display;
return this;
}

// 应用设置
void applyConfig(Computer computer) {
computer.cpu = this.cpu;
computer.graphicsCard = this.graphicsCard;
computer.motherBoard = this.motherBoard;
computer.memory = this.memory;
computer.hardDsik = this.hardDsik;
computer.display = this.display;
}

// 创建
public Computer create() {
Computer computer = new Computer();
applyConfig(computer);
return computer;
}

}

}


使用

// Builder模式
Computer computer = new Computer.Builder().setCpu("i7").create();


Builder模式的好处:

1.减少大量不必要的get,set方法,并且这种做法规定了只有在初始化的时候可以设置参数属性。用户不需要再开发过程中另外考虑是否改变属性参数。

2.良好的封装性,使用建造者模式可以使用户不需要知道内部细节也能够使用,因为内部初始化了参数属性。

3.独立,容易拓展。

Builder模式的缺点:

1.消耗内存,产生多余的Builder对象,消耗内存。

以上为我初学者的看法,如果有不足的地方欢迎指导。 : )
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: