java 生成器模式空指针异常错误

mzsu5hc0  于 2022-11-27  发布在  Java
关注(0)|答案(2)|浏览(134)

运行下面的代码时出现空指针异常:

public class Engine{

    private String name = null;
    private Mercedes m = null;

    private Engine() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Mercedes getM() {
        return m;
    }

    public void setM(Mercedes m) {
        this.m = m;
    }

    public static EngineBuilder builder() {
        return new EngineBuilder();
    }

    public static class EngineBuilder {
        private Engine e = null;

        public EngineBuilder builder() {
            e = new Engine();
            return this;
        }

        public Engine build() {
            return this.e;
        }

        public EngineBuilder setName(String name) {
            this.e.setName(name);
            return this;
        }

        public EngineBuilder setM(Mercedes m) {
            this.e.setM(m);
            return this;
        }

    }
    public static void main(String[] args) {
        EngineBuilder builder = Engine.builder();
        builder.setName("test");
                
        Engine e = builder.build();

    }
}
}

我希望Builder模式可以工作,但我得到了
线程“main”中出现异常java.lang.NullPointerException:无法调用“Engine.setName(String)”,因为“this.e”为空

pvcm50d1

pvcm50d11#

在您的代码中,EngineBuilder类只有默认的构造函数,它不会初始化引擎对象。请编写一个初始化所需对象的构造函数。

ssgvzors

ssgvzors2#

生成器未正确实现。它应该是这样的(示例仅针对参数名称)

public class Engine{

    private String name = null;
    
    private Engine() {}

    public String getName() {
        return name;
    }

    public static EngineBuilder builder() {
        return new EngineBuilder();
    }

    public static class EngineBuilder {
        private String name = null;

        public Engine build() {

            Engine engine = new Engine();
            engine.name = this.name
            return new Engine();
        }

        public EngineBuilder setName(String name) {
            this.name = name;
            return this;
        }

    }
    public static void main(String[] args) {
        EngineBuilder builder = Engine.builder();
        builder.setName("test");
                
        Engine e = builder.build();

    }
}
}

相关问题