eff多可选构造参数可考虑构建器
2012-07-12 12:06
232 查看
1 package eff; 2 3 /** 4 * 如果类的构造器或者静态工厂中具有多个参数,设计这种类时, 5 * Builder模式就是不错的选择,特别是大多数参数都是课选的时候。 6 * 相对于javaBean较为安全,适用于多个可选参数的对象创建。 7 * 8 * @author lw 9 * 10 */ 11 public class NutritionFacts { 12 // required 13 private final int servingSize; 14 private final int servings; 15 // optional 16 private final int calories; 17 private final int fat; 18 private final int sodium; 19 private final int carbohydrate; 20 21 /** 构建器 */ 22 public static class Builder implements IBuilder<NutritionFacts> { 23 private final int servingSize; 24 private final int servings; 25 private int calories; 26 private int fat; 27 private int sodium; 28 private int carbohydrate; 29 30 31 public Builder(int servingSize, int servings) { 32 this.servingSize = servingSize; 33 this.servings = servings; 34 } 35 36 public Builder calories(int val) { 37 calories = val; 38 return this; 39 } 40 41 public Builder fat(int val) { 42 fat = val; 43 return this; 44 } 45 46 public Builder sodium(int val) { 47 sodium = val; 48 return this; 49 } 50 51 public Builder carbohydrate(int val) { 52 carbohydrate = val; 53 return this; 54 } 55 56 public NutritionFacts build() { 57 return new NutritionFacts(this); 58 } 59 } 60 61 public NutritionFacts(Builder builder) { 62 servingSize = builder.servingSize; 63 servings = builder.servings; 64 calories = builder.calories; 65 fat = builder.fat; 66 sodium = builder.sodium; 67 carbohydrate = builder.carbohydrate; 68 } 69 70 public int getServingSize() { 71 return servingSize; 72 } 73 74 public int getServings() { 75 return servings; 76 } 77 78 public int getCalories() { 79 return calories; 80 } 81 82 public int getFat() { 83 return fat; 84 } 85 86 public int getSodium() { 87 return sodium; 88 } 89 90 public int getCarbohydrate() { 91 return carbohydrate; 92 } 93 94 }
相关文章推荐
- 遇到构造器中有多个可选参数时要考虑用构建器
- 第二条:遇到多个构造参数时要考虑用构建器
- 2、遇到多个构造参数的时候需要考虑使用构建器(effective java)
- 学习记录--遇到多个构造参数时考虑用构建器
- Effective Java之多个构造参数考虑用构建器(二)
- Item 2---遇到构造器具有多个参数时,要考虑用构建器;Builder模式
- 可选int参数'cid'存在,但由于被声明为基本类型而无法转换为空值。考虑将其声明为相应基元类型的对象包装。
- 遇到多个构造器参数时要考虑用构建器
- Java学习笔记2:当构造方法有多个参数时考虑使用Builder
- 多个构造器参数时要考虑用构建器
- Android 编码规范:(二)遇到多个构造器参数时要考虑用构建器
- 第2条:遇到多个构造器参数时要考虑用构建器
- 遇到多个构造器参数时要考虑用构建器
- Effective Java 第二条:遇到多个构造器参数时要考虑用构建器
- Android 编码规范:(二)遇到多个构造器参数时要考虑用构建器
- 遇到多个构造器参数时要考虑用构建器——Effective Java 读书笔记
- 遇到多个构造器参数时要考虑用构建器Bulider
- Effective Java 读书笔记(二):遇到多个构造器参数时要考虑用构建器
- Effective Java 2 -- 遇到多个构造器参数的时候考虑构建器
- 遇到多个构造器参数时考虑使用构建器