读书笔记——遇到多个构造器时要考虑用Builder

1、多个构造器的坏处

     好多种参数,特别是参数特别多时,用户调用非常不方便,如果不对照文档,根本不知道哪个参数表示什么含义,对于同类型的参数,如果传参错误,编译时也检查不出来,只有运行时才会发现不对。总之,不方便用户调用。

2、利用Java Bean的方式的坏处

    对于多个参数,如果让用户调用时能够知道各个参数都是什么含义,可以采用Java Bean的方法,但是这种方式有严重的缺点,就是因为构造过程被分到几个调用中,因此可能处于不一致的状态,因此可能参数错误,而这种错误与包含错误代码大相径庭,调试起来非常困难。

3、利用Builder

    对于多种参数最好的解决办法就是利用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 {
        private final int servingSize;
        private final int servings;
        
        private int calories = 0;
        private int fat = 0;
        private int carbohydrate = 0;
        private int sodium = 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 carbohydrate(int val) {
            carbohydrate = val;
            return this;
        }
        
        public Builder sodium(int val) {
            sodium = val;
            return this;
        }
        
        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }
    
    public NutritionFacts(Builder builder) {
        servingSize = builder.servingSize;
        servings = builder.servings;
        calories = builder.calories;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbohydrate;
    }    
}

 

     

posted on 2012-04-18 10:44  亭子  阅读(352)  评论(0编辑  收藏  举报

导航