繁体   English   中英

使用什么正确的设计模式

[英]What would be the correct design pattern to use

所以我有一个生成器接口:

public interface Generator
{
    public Generator getInstance(); (The problem is here - methods in interface can't be static)
    public Account generate() throws WalletInitializationException;
}

以及其他 2 个实现该接口的类。

Now I'd like to have a GeneratorFactory class that receives the class Class object, invokes the getInstance() method and returns the class object.

像这样的东西:

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() 方法是实例方法而不是 static 方法,因此我无法使用实例的 null 参数调用 invoke()。

我想做一个工厂的抽象 class ,其中包含一个 getInstance() 方法和一个抽象 generate() 方法,用于生成器 class 来实现它,这是正确的方法吗?

我最终没有使用 singleton。 只需使用具有以下使用反射的方法的常规工厂:

    public static Generator getGenerator(Class<? extends Generator> generatorClass)
    {
        try
        {
            return generatorClass.newInstance();
        }
        catch (Exception e)
        {
            return null;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM