Builder中有效Java模式 [英] Builder Pattern in Effective Java
问题描述
具有多个属性的类及其构建器类:
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;
返回这个;
}
public Builder carbo(int c){
this.carbo = c;
返回这个;
}
public NutritionalFacts build(){
return new NutritionalFacts(this);
}
}
私人营养物品(生成器b){
this.sodium = b.sodium;
this.fat = b.fat;
this.carbo = b.carbo;
}
}
我尝试使用上述类的类: / p>
public class Main {
public static void main(String args []){
NutritionalFacts n =
new NutritionalFacts.Builder(10).carbo(23).fat(1).build();
}
}
我收到以下编译器错误:
包含
effectivejava.BuilderPattern.NutritionalFacts.Builder
的附加实例
NutritionalFacts n = new
NutritionalFacts.Builder(10).carbo(23).fat(1).build();
我不了解消息的含义。请解释。上面的代码与Bloch在他的书中提出的例子相似。
使构建器成为静态
类。然后它会工作。如果它是非静态的,它将需要一个它自己的类的一个实例,而且这个点不是有一个实例,甚至禁止在没有构建器的情况下进行实例。
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
这篇关于Builder中有效Java模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!