gpt4 book ai didi

java - 枚举样式工厂作为 Java 中的内部枚举

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:23 28 4
gpt4 key购买 nike

我尝试将枚举样式的工厂模式实现为内部枚举,但它没有用。有没有不将内部枚举分离到新文件中的解决方案?换句话说,内部枚举样式的工厂模式是否可能?

代码如下。

public class SampleParent {

private class InnerChild { }
private class InnerChildA extends InnerChild { }
private class InnerChildB extends InnerChild { }
private class InnerChildC extends InnerChild { }

enum InnerChildEnum {
CHILD_A {
@Override
public InnerChild getInstance() {
return new InnerChildA(); // compile error
}
},
CHILD_B {
@Override
public InnerChild getInstance() {
return new SampleParent.InnerChildB(); // compile error
}
},
CHILD_C {
@Override
public InnerChild getInstance() {
return SampleParent.new InnerChildC(); // compile error
}
},
;

public abstract InnerChild getInstance();
}

private static class InnerChildFactoryEnumStyled {
public static InnerChild getInnerChild(InnerChildEnum child) {
return child.getInstance();
}
}


public static void main(String[] args) {

// I want to write this way
InnerChild child = InnerChildFactoryEnumStyled.getInnerChild(InnerChildEnum.CHILD_A);
}
}

编译错误信息如下

$ javac SampleParent.java 
SampleParent.java:12: error: non-static variable this cannot be referenced from a static context
return new InnerChildA();
^
SampleParent.java:18: error: non-static variable this cannot be referenced from a static context
return new SampleParent.InnerChildB();
^
SampleParent.java:24: error: cannot find symbol
return SampleParent.new InnerChildC();
^
symbol: variable SampleParent
3 errors

最佳答案

您的内部类不是静态的,因此它们必须引用封闭类 SampleParent 的实例。将您的类声明更改为

private static class InnerChild { }
private static class InnerChildA extends InnerChild { }
private static class InnerChildB extends InnerChild { }
private static class InnerChildC extends InnerChild { }

你可以。 G。 return new InnerChildA(); 在你的枚举中。

关于java - 枚举样式工厂作为 Java 中的内部枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42978524/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com