遇到多个构造器参数时要考虑用构造器
2016-02-18 10:41
429 查看
一般的重叠构造器模式:
改进:Builder模式:
public class NutritionFacts{ private final int one; private final int two; private final int three; public NutritionFacts(int one,int two,int three){ this.one = one; this.two = two; } public NutritionFacts(int one){ this(one,0); } public NutritionFacts(int one,int two){ this(one,two,0); } } //调用的时候 NutritionFacts nt = new NutritionFacts(0,0,0); //缺点 :重叠构造器模式,有许多参数的时候,难编写和阅读;
改进:Builder模式:
public class NutritionFacts{ private final int one; private final int two; private final int three; private NutritionFacts(Bulider builder){ one = builder.one; two = builder.two; three = builder.three; } public static class Builder{ private String name; private int one = 0; private int two = 0 ; private int three = 0; public Builder(String name){ this.name = name; } public Builder one(int value){ one = value; reture this; } public Builder two(int value){ two = value; reture this; } public Builder two(int value){ two = value; reture this; } //调用的时候,最后实例化外部类 public NutritionFacts build(){ return new NutritionFacts(this); } } }
相关文章推荐
- [转]实现微信浏览器内打开App Store链接
- 克隆KVM虚拟机
- C#设计模式09-装饰模式
- 多线程下载 显示进度 速度(转)
- JSONKit 在Xcode7下的问题
- C\C++常用库函数实现
- 【转】Oracle Object type 对象类型详解
- GCC-4.8.2 的安装
- convertRect
- 导出csv文件能在浏览器打开
- EF实现主从表自动生成主键保存
- 寻找SQL注入点
- 粗略地在iOS中使用URLManager架构
- mysql分表和表分区详解
- Shell脚本,包含了[分支 循环 数组 搜索 运算等基本功能]
- 线程池三:AsyncTask线程池
- Android Graphics (一) :Paint
- Convergent Encryption - 云存储的去重与加密
- 文字多行缩进 css 兼容浏览器
- 10个linux网络和监控命令