是否可以有一个包含对象构造函数的枚举?
我正在测试一种不同的模式。我已经让代码在 switch
语句中运行,但我想尝试一些更不拘一格的东西......出于研究目的。
假设我有 4 个类,Class1
、Class2
、Class3
和 Class4
,它们都扩展了 BaseClass< /代码>。我想将它们放入
enum
中,如下所示:
enum ClassFactories {
Class1(Class1.class),
Class2(Class2.class),
Class3(Class3.class),
Class4(Class4.class);
private final Class factory;
ClassFactories(Class factory) {
this.factory = factory;
}
public BaseClass generate() {
BaseClass b = null;
try {
b = (BaseClass)this.factory.newInstance();
} catch (Exception e) {
// handle any exceptions
}
return f;
}
}
在传递 int
的工厂方法中,我希望能够执行以下操作
public void fakeMethod(int type) {
BaseClass someClass = ClassFactories.values()[type].generate();
someClass.doStuff();
}
:更干净/更简单的方法?我不太关心可读性(现在),我只是好奇这是否可能。
I'm testing out a different sort of pattern. I've already got the code working in a switch
statement, but I'd like to try something a little more ecclectic... for research purposes.
Say I have 4 classes, Class1
, Class2
, Class3
, and Class4
that all extend BaseClass
. I want to put them into an enum
, like so:
enum ClassFactories {
Class1(Class1.class),
Class2(Class2.class),
Class3(Class3.class),
Class4(Class4.class);
private final Class factory;
ClassFactories(Class factory) {
this.factory = factory;
}
public BaseClass generate() {
BaseClass b = null;
try {
b = (BaseClass)this.factory.newInstance();
} catch (Exception e) {
// handle any exceptions
}
return f;
}
}
In a factory method that is passed an int
, I want to be able to do something like this:
public void fakeMethod(int type) {
BaseClass someClass = ClassFactories.values()[type].generate();
someClass.doStuff();
}
Is there a cleaner/easier way of doing this? I'm not so much concerned with readability (right now), I'm just curious if this is possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这是可能的。类似于“模板方法”的方法。因此,例如
INVOCATION CODE
使用静态导入,调用此枚举的客户端代码将如下所示:
或者
Yes, this is possible. Something like a 'Template Method' approach. So for example
INVOCATION CODE
With the use of static imports, the client code calling this enumeration would look like:
Or