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 }