设计模式之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对象,消耗内存。
以上为我初学者的看法,如果有不足的地方欢迎指导。 : )
相关文章推荐
- UITableView的代理方法viewForHeaderInSection不执行的原因
- IBM CleanQuest使用方法
- hdu 1159 Common Subsequence
- View requires API level 14 (current min is 8): <GridLayout>
- discuz X3.2 开启QQ互联后,点击登录以后报错:(1054) Unknown column 'conuintoken' in 'field list'
- Cf Round #361 (Div. 2) 689D. Friends and Subsequences
- UITableViewCell 中的单选控制 UITableViewCellAccessoryCheckmark
- org.openqa.selenium.remote.SessionNotFoundException: The FirefoxDriver cannot be used after quit() was called.
- Android进阶UI之使用TextInputLayout创建一个登陆界面
- UESTC149 解救小Q
- Druid 数据库用户密码加密 代码实现
- UI面板拖放
- UITableViewController类预置模板详解(部分一)
- HDU 1005 Number Sequence[数论]
- NSString之 doubleValue floatValue intValue integerValue longLongValue
- arm交叉编译器gnueabi、none-eabi、arm-eabi、gnueabihf、gnueabi区别
- UITextField 输入限制
- ubuntu bluetooth 配对过程
- easyUI 消息框的API
- POJ 3080 Blue Jeans