Effective Java Second Edition --- Builder Pattern

如果类的构造器或者静态工厂中有多个参数,设计这种类时,Builder模式是一种不错的选择,特别是当大多数参数是可选的时候。

与使用传统的重载构造函数模式相比,使用Builder模式的客户端代码更易于阅读和编写,构造器也比javabeens更加安全。

代码如下:

 /**
* Created by zhanga.fnst on 2016/3/14.
*/
public class NutritionFacts {
private final int servingSize;
private final int servings;
private final int calories;
private final int flat;
private final int sodium;
private final int carbohydrate; public static class Builder{
//required parameters
private final int servingSize;
private final int servings; //Optional parameters
private int calories = 0;
private int flat = 0;
private int sodium = 0;
private int carbohydrate = 0; public Builder(int servingSize,int servings){
this.servingSize = servingSize;
this.servings = servings;
} public Builder calories(int val){
calories = val;
return this;
} public Builder flat(int val){
flat = val;
return this;
} public Builder carbohydrate(int val){
carbohydrate = val;
return this;
} public Builder sodium(int val){
sodium = val;
return this;
} public NutritionFacts build(){
return new NutritionFacts(this);
}
} private NutritionFacts(Builder builder){
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
flat = builder.flat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
}

main方法:

 /**
* Created by zhanga.fnst on 2016/3/14.
*/
public class TestMain {
NutritionFacts cocaCola = new NutritionFacts.Builder(240,8).
calories(100).sodium(35).carbohydrate(27).build();
}
上一篇:iOS应用程序开发之应用间的跳转(用着微信等第三方分享登陆)


下一篇:SimpleAdapter的使用