英文:
What would be the correct design pattern to use
问题
所以我有一个生成器接口:
public interface Generator
{
public Generator getInstance(); // (问题在这里 - 接口中的方法不能是静态的)
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((需要有实例的地方) null, null); // (应该是运行时错误)
}
}
但是由于getInstance()方法是实例方法而不是静态方法,我不能使用null参数来调用invoke()以获取实例。
我考虑过创建一个工厂的抽象类,其中包含一个getInstance()方法和一个抽象的generate()方法,以供生成器类进行实现,这是否是正确的方法?
英文:
So I have a Generator interface:
public interface Generator
{
public Generator getInstance(); (The problem is here - methods in interface can't be static)
public Account generate() throws WalletInitializationException;
}
And 2 other classes which implements the interface.
Now I'd like to have a GeneratorFactory class that receives the class Class object, invokes the getInstance() method and returns the class object.
Something like this:
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)
}
}
But since the getInstance() method is an instance method and not a static method, I can't call invoke() with a null parameter for the instance.
I thought of doing an abstract class of a Factory which contains a getInstance() method and an abstract generate() method for the generators class to implement it, will that be the correct approach?
答案1
得分: 0
我最终没有使用单例模式。只是使用了一个常规工厂,其中包含以下使用反射的方法:
public static Generator getGenerator(Class<? extends Generator> generatorClass)
{
try
{
return generatorClass.newInstance();
}
catch (Exception e)
{
return null;
}
}
英文:
I've ended up not using singleton. Just using a regular factory with the following method that uses reflection:
public static Generator getGenerator(Class<? extends Generator> generatorClass)
{
try
{
return generatorClass.newInstance();
}
catch (Exception e)
{
return null;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论