C++工厂-> Java 工厂?
当我第一次学习 C++ 时,我看到这篇关于工厂的文章, 可插拔 C++ 工厂,从那时起我就在 C++ 中的工厂中使用了该模式。现在,我最近一直在做Java,并且不止一次我想使用工厂,但我似乎无法找到一种在编译时扩展工厂的方法。
我能想到的 Java 工厂的任何实现都涉及告诉实际工厂类所有底层类,这是相当次优的。
那么,如何让一个类的所有子类在编译时/程序实例化时将自己注册到静态字典中?
编辑 看来我的问题太模糊了。让我详细说明一下,
在 Java 中,如果我要尝试像这样复制此模式: Factory.java
abstract class Factory {
private static Dictionary<int, Factory> dict;
public Factory(int index) {
dict[int] = self;
}
public Foo getFoo(int index) {return dict[index].createFoo();}
protected abstract Foo makeFoo();
}
Derived.java
class Derived extends Factory {
public Derived() {super(DERIVED_INDEX);}
private static Derived tmp = new Derived();
public Foo makeFoo() {return new FooImplementation();}
}
工厂不会使用对 Derived 的引用进行更新(因此不会创建 Derived 实例),除非我自己手动注册它,这违背了拥有静态 tmp 成员的目的。
When I was first learning C++, I came across this article about factories,
Pluggable C++ Factory, and ever since I've used that pattern for my factories in C++. Now, I've been doing Java recently and on more than one occasion I've wanted to use a factory, but I can't seem to figure out a way to extend the factory at compile time.
Any implementation of a factory I can think of in Java involves telling the actual factory class about all of the underlying classes, which is rather suboptimal.
So, how can I get all subclasses of a class to register themselves in a static dictionary at compile time/program instantiation?
EDIT
It seems that my question was too vague. Let me elaborate,
In Java if I were to try to replicate this pattern like so:
Factory.java
abstract class Factory {
private static Dictionary<int, Factory> dict;
public Factory(int index) {
dict[int] = self;
}
public Foo getFoo(int index) {return dict[index].createFoo();}
protected abstract Foo makeFoo();
}
Derived.java
class Derived extends Factory {
public Derived() {super(DERIVED_INDEX);}
private static Derived tmp = new Derived();
public Foo makeFoo() {return new FooImplementation();}
}
The factory won't update with the reference to Derived (and thus won't create Derived instances) unless I manually register it myself, which defeats the purpose of having the static tmp member.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为 ServiceLoader 类可以在这里帮助您。
I think the ServiceLoader class can help you here.
考虑使用反射来实现工厂方法。
Think of implementing Factory Method using Reflection.
您可能会发现 Reflections 库很有用。
使用此库,您可以定义一个接口和一个工厂,该工厂可以创建该接口的任何实现(通过搜索这些实现)
You might find the Reflections library useful.
Using this library you can define an interface and a factory which can create any implementation of that interface (by searching for those implementations)