C ++工厂 - > Java工厂?

时间:2011-04-12 02:27:45

标签: java c++ factory-pattern

当我第一次学习C ++时,我遇到了关于工厂的这篇文章, Pluggable C++ Factory,自从我将这种模式用于我的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成员的目的。

3 个答案:

答案 0 :(得分:0)

我认为ServiceLoader课程可以帮到你。

答案 1 :(得分:0)

考虑使用Reflection实现Factory方法。

答案 2 :(得分:0)

您可能会发现Reflections库很有用。

  

使用思考可以查询元数据,例如:

* 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 

使用此库,您可以定义一个接口和工厂,可以创建该接口的任何实现(通过搜索这些实现)