Effective Java Item2:Consider a builder when faced with many constructor parameters

Item2:Consider a builder when faced with many constructor parameters

当构造方法有多个参数时,可以考虑使用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 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 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;

    }

}

使用方式:

public class Test {

    public static void main(String[] args) {

        NutritionFacts nf = new NutritionFacts.Builder(200, 80)

                .calories(100).sodium(35).carbohydrate(20).build();

    }

}

 

你可能感兴趣的:(Effective Java)