且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Builder中有效Java模式

更新时间:2023-12-02 20:21:22

使构建器成为静态类。然后它会工作。如果它是非静态的,它将需要一个它自己的类的一个实例,而且这个点不是有一个实例,甚至禁止在没有构建器的情况下进行实例。

  public class NutritionFacts {
public static class Builder {
}
}

参考:嵌套类


I have recently started to read Effective Java by Joshua Bloch. I found the idea of the Builder pattern [Item 2 in the book] really interesting. I tried to implement it in my project but there were compilation errors. Following is in essence what I was trying to do:

The class with multiple attributes and its builder class:

public class NutritionalFacts {
    private int sodium;
    private int fat;
    private int carbo;

    public class Builder {
        private int sodium;
        private int fat;
        private int carbo;

        public Builder(int s) {
            this.sodium = s;
        }

        public Builder fat(int f) {
            this.fat = f;
            return this;
        }

        public Builder carbo(int c) {
            this.carbo = c;
            return this;
        }

        public NutritionalFacts build() {
            return new NutritionalFacts(this);
        }
    }

    private NutritionalFacts(Builder b) {
        this.sodium = b.sodium;
        this.fat = b.fat;
        this.carbo = b.carbo;
    }
}

Class where I try to use the above class:

public class Main {
    public static void main(String args[]) {
        NutritionalFacts n = 
            new NutritionalFacts.Builder(10).carbo(23).fat(1).build();
    }
}

I am getting the following compiler error:

an enclosing instance that contains effectivejava.BuilderPattern.NutritionalFacts.Builder is required NutritionalFacts n = new NutritionalFacts.Builder(10).carbo(23).fat(1).build();

I do not understand what the message means. Please explain. The above code is similar to the example suggested by Bloch in his book.

Make the builder a static class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.

public class NutritionFacts {
    public static class Builder {
    }
}

Reference: Nested classes