Effective Java 第二条:遇到多个构造器参数时要考虑用构建器

   遇到多个构造器参数的时候,也可以用JavaBeans模式(无参构造器,提供setter方法),但是不是线程安全的。

   还有第三种代替方法,既能保证像重叠构造器模式那样的安全性,也能保证像JavaBeans模式那么好的可读性。就是Builder模式。

public class NutritionFacts {
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    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 final int calories=0;
        private final int fat=0;
        private final int sodium=0;
        private final 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 fat(int val)
            {fat = val;    return this;}
        public Builder sodium(int val)
            {sodium = val;    return this;}
        public Builder carbohydrate(int val)
            {carbohydrate = val;    return this;}
                                                 
        public NutritionFacts build(){
            return new NutritionFacts(this);
        }
    }
    // 私有的构造器
    private NutritionFacts(Builder builder){
        servingSize = builder.servingSize;
        servings = builder.servings;
        calories = builder.calories;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbohydrate;
    }
}

客户端代码:

NutritionFacts cocaCola = new NutritionFacts.Builder(240,8).
    calories(100).sodium(35).carbohydrate(27).build();

你可能感兴趣的:(Builder模式)