什么是正确的设计模式可供使用

huangapple go评论64阅读模式
英文:

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&#39;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&lt;Generator&gt; generatorClass)
	{
		return (Generator) generatorClass.getMethod(&quot;getInstance&quot;, 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&lt;? extends Generator&gt; generatorClass)
	{
		try
		{
			return generatorClass.newInstance();
		}
		catch (Exception e)
		{
			return null;
		}
	}

huangapple
  • 本文由 发表于 2020年5月29日 17:45:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/62083080.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定