Effective Java 中的建造者模式 [英] Builder Pattern in Effective Java

查看:20
本文介绍了Effective Java 中的建造者模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始阅读 Joshua Bloch 的 Effective Java.我发现 Builder 模式 [本书中的第 2 项] 的想法非常有趣.我试图在我的项目中实现它,但出现编译错误.以下是我试图做的本质上:

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:

一个封闭的实例,包含有效的java.BuilderPattern.NutritionalFacts.Builder是必须的营养成分 n = 新NutritionalFacts.Builder(10).carbo(23).fat(1).build();

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

我不明白这条消息是什么意思.请解释.上面的代码类似于Bloch在他的书中建议的例子.

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

推荐答案

使构建器成为 static 类.然后它会起作用.如果它是非静态的,它将需要一个其所属类的实例——重点是没有它的实例,甚至禁止在没有构建器的情况下创建实例.

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 {
    }
}

参考:嵌套类

这篇关于Effective Java 中的建造者模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆