简体   繁体   English

使用什么正确的设计模式

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

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.以及其他 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. 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.但是由于 getInstance() 方法是实例方法而不是 static 方法,因此我无法使用实例的 null 参数调用 invoke()。

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

I've ended up not using singleton.我最终没有使用 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;
        }
    }

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

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