effectiveJava(2)使用构建器

如果类的构造器或者静态工厂中具有多个参数,设计这样的类时,考虑使用Builder模式。尤其是大多数参数都是可选的时候,与使用传统的重叠构造器模式相比,使用

builder模式的客户端代码将更易于阅读和编写,构建器也比JavaBeans更加安全。示例如下

 1 public class NutritionFacts {
 2     private final int servingSize;
 3     private final int servings;
 4     private final int calories;
 5     private final int fat;
 6     private final int sodium;
 7     private final int carbohydrate;
 8 
 9     public NutritionFacts(Builder builder) {
10         servingSize = builder.servingSize;
11         servings = builder.servings;
12         calories = builder.calories;
13         fat = builder.fat;
14         sodium = builder.sodium;
15         carbohydrate = builder.carbohydrate;
16     }
17 
18     public static class Builder {
19         private final int servingSize;
20         private final int servings;
21         private int calories = 0;
22         private int fat = 0;
23         private int carbohydrate = 0;
24         private int sodium = 0;
25 
26         public Builder(int servingSize, int servings) {
27             this.servingSize = servingSize;
28             this.servings = servings;
29         }
30 
31         public Builder calories(int val) {
32             calories = val;
33             return this;
34         }
35 
36         public Builder fat(int val) {
37             fat = val;
38             return this;
39         }
40 
41         public Builder carbohydrate(int val) {
42             carbohydrate = val;
43             return this;
44         }
45 
46         public Builder sodium(int val) {
47             sodium = val;
48             return this;
49         }
50 
51         public NutritionFacts build() {
52             return new NutritionFacts(this);
53         }
54     }
55 }

猜你喜欢

转载自www.cnblogs.com/dgq-blog/p/8943556.html