美文网首页Effective Java Sencond Edition
Effective Java 第2条:遇到多个构造器参数是要考虑

Effective Java 第2条:遇到多个构造器参数是要考虑

作者: linyk3 | 来源:发表于2018-12-18 21:56 被阅读0次

静态工厂和构造器共同的局限性: 不能扩展到大量的可选参数.

这时可以考虑构建器 builder:

public static 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 paramters
        private final int servingSize;
        private final int servings;

        // Optional paramters - initialized to default values
        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;
    }
}

builder 调用示例:

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

相关文章

网友评论

    本文标题:Effective Java 第2条:遇到多个构造器参数是要考虑

    本文链接:https://www.haomeiwen.com/subject/hjyrkqtx.html