vendredi 29 mai 2020

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.

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?

Aucun commentaire:

Enregistrer un commentaire