当我第一次学习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();}
}除非我自己手动注册,否则工厂不会使用派生引用更新(因此不会创建派生实例),这就违背了拥有静态tmp成员的目的。
发布于 2011-04-12 02:34:20
我认为ServiceLoader课在这里可以帮助你。
发布于 2011-04-12 02:49:06
考虑使用反射实现工厂方法。
发布于 2011-04-12 07:04:29
您可能会发现反思库很有用。
使用反射,您可以查询元数据,如:
* get all subtypes of some type
* get all types/methods/fields annotated with some annotation, w/o annotation parameters matching
* get all resources matching matching a regular expression 使用这个库,您可以定义一个接口和一个工厂,它可以创建该接口的任何实现(通过搜索这些实现)。
https://stackoverflow.com/questions/5629742
复制相似问题