所以我有一个Generator界面:
public interface Generator
{
public Generator getInstance(); (The problem is here - methods in interface can't be static)
public Account generate() throws WalletInitializationException;
}
和另外两个实现该接口的类。
现在,我希望有一个GeneratorFactory类,该类可以接收类Class对象,调用getInstance()方法并返回该类对象。
类似这样的东西:
public class GeneratorFactory
{
private GeneratorFactory()
{
}
public static Generator getGenerator(Class<Generator> generatorClass)
{
return (Generator) generatorClass.getMethod("getInstance", null).invoke((Need to have instance) null, null); (Should be runtime error)
}
}
但是由于getInstance()方法是一个实例方法,而不是静态方法,所以我无法使用该实例的null参数调用invoke()。
我想到做一个Factory的抽象类,它包含一个getInstance()方法和一个抽象的generate()方法,供generators类实现,这是正确的方法吗?
答案 0 :(得分:0)
我最终不使用单例。只需将常规工厂与以下使用反射的方法一起使用即可:
public static Generator getGenerator(Class<? extends Generator> generatorClass)
{
try
{
return generatorClass.newInstance();
}
catch (Exception e)
{
return null;
}
}