Java 正确的设计模式是什么
因此,我有一个生成器接口:Java 正确的设计模式是什么,java,design-patterns,Java,Design Patterns,因此,我有一个生成器接口: public interface Generator { public Generator getInstance(); (The problem is here - methods in interface can't be static) public Account generate() throws WalletInitializationException; } 以及实现该接口的其他两个类 现在我想要一个GeneratorFactory类,
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()方法并返回class对象
大概是这样的:
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)
}
}
公共类生成器工厂
{
私人发电厂()
{
}
公共静态生成器getGenerator(类生成器类)
{
return(Generator)generatorClass.getMethod(“getInstance”,null).invoke((需要有实例)null,null);(应该是运行时错误)
}
}
但是由于getInstance()方法是一个实例方法而不是静态方法,因此我不能使用实例的null参数调用invoke()
我想为generators类创建一个包含getInstance()方法和abstract generate()方法的工厂抽象类来实现它,这是正确的方法吗?我最终没有使用singleton。仅使用常规工厂,使用以下使用反射的方法:
public static Generator getGenerator(Class<? extends Generator> generatorClass)
{
try
{
return generatorClass.newInstance();
}
catch (Exception e)
{
return null;
}
}
publicstaticgenerator getGenerator(ClassSo,基本上,你想为工厂创建一个工厂?类似的,我希望程序员只需要处理一个工厂就可以获得其他实例(工厂).也许只有我一个人,但我很难理解你想要实现什么。如果你提供一点用例,即使是伪代码,也会很有帮助。顺便说一句,关于设计模式等的问题通常更适合。我不是说你不会得到答案,但SE上的人更愿意深入细节这是关于设计的。那么return generatorClass.newInstance();
或return generatorClass.newInstance().getInstance();
中的
?这对您有用吗?您必须尝试-捕获可能的异常或给方法一个抛出
声明。您不想在getGenerator中使用反射吗?