簡體   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