Builder模式

//Builder Pattern
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 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;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbohydrate;
    }

    public static void main(String[] args)
    {
        NutritionFacts cocaCola = new NutritionFacts.Builder(250,9).calories(100).sodium(12).carbohydrate(34).fat(10).build();
    }
}

 

刚照着书本敲完时,对main函数里面的静态内部类的实例化感到很疑惑:为什么静态的也需要实例化?

查了一些资料后得知,static修饰的内部类不是说它是静态类,而是说它是外部类的静态成员,静态内部类不会依赖于外部类的实例。

 

//内部类的实例化:
Parent p = new Parent();
Parent.Inner i = p.new Inner();

//静态内部类的实例化:
Parent.Inner i = new Parent.Inner();

 

参考资料:

内部类及静态内部类的实例化

Java中静态类为什么也可以实例化

posted @ 2017-09-10 16:16  枯木fc  阅读(160)  评论(0编辑  收藏  举报