簡體   English   中英

從字典列表中返回一個新對象

[英]return a new object from dictionary listing

我有一個程序,我正在使用一個管理器維護一個泛型類的字典。 我希望能夠注冊新類型(使用多態)並將其存儲在字典中(使用基於整數的鍵),然后能夠根據存儲的類型創建新對象。 這是我有的:

Dictionary<uint,GenericClass> mGenericLibrary = new Dictionary<uint,GenericClass>();

public GenericClass GetNewGenericType(uint id)
{
     return mGenericLibrary[id];
}

字典將保存GenericClass類型的子類,即GenericClassSub1,GenericClassSub2,GenericClassSub3等....

此時我想在另一個類中調用GetNewGenericType並根據注冊的整數ID獲取一個新對象,該對象屬於一個子類型。

我怎樣才能做到這一點?

你要做的是被稱為“ 工廠模式 ”。 而不是包含您想要創建的類型的字典,而是使用字典保存類來生成您想要創建的類型(“工廠”)。

public abstract GenericFactory
{
    public abstract GenericClass CreateInstance();
}

public GenericClassSub1Factory : GenericFactory
{
    public override GenericClass CreateInstance()
    {
        return new GenericClassSub1();
    }
}

public GenericClassSub2Factory : GenericFactory
{
    public override BaseClass CreateInstance()
    {
        return new GenericClassSub2();
    }
}

然后你聲明你的字典並像這樣使用它:

class MyClassFactory
{
    Dictionary<uint,GenericFactory> mGenericLibrary = new Dictionary<uint,GenericFactory>();

    public void RegisterFactory(uint id, GenericFactory factory)
    {
        mGenericLibrary[id] = factory;
    }

    public GenericClass GetNewGenericType(uint id)
    {
         return mGenericLibrary[id].CreateInstance();
    }
}


void Example()
{
    var factory = new MyClassFactory();

    factory.RegisterFactory(1, new GenericClassSub1Factory());
    factory.RegisterFactory(2, new GenericClassSub2Factory());
    factory.RegisterFactory(3, new GenericClassSub3Factory());

    var item1 = factory.GetNewGenericType(1); //Contains a new GenericClassSub1;
    var item2 = factory.GetNewGenericType(2); //Contains a new GenericClassSub2;
    var item3 = factory.GetNewGenericType(3); //Contains a new GenericClassSub3;
}

更新:

如果您不想讓人們制作工廠類,您仍然可以通過委托來完成工廠模式,那么最終用戶需要更少的代碼才能添加到工廠。

class MyClassFactory
{
    Dictionary<uint,Func<GenericClass>> mGenericLibrary = new Dictionary<uint,Func<GenericClass>>();

    public void RegisterFactory(uint id, Func<GenericClass> factory)
    {
        mGenericLibrary[id] = factory;
    }

    public GenericClass GetNewGenericType(uint id)
    {
         //This could be one line, but i think mGenericLibrary[id]() looks too weird.
         Func<GenericClass> factory = mGenericLibrary[id];
         return factory();
    }
}

    void Example()
{
    var factory = new MyClassFactory();

    factory.RegisterFactory(1, () => new GenericClassSub1());
    factory.RegisterFactory(2, () => new GenericClassSub2());
    factory.RegisterFactory(3, () => new GenericClassSub3());

    var item1 = factory.GetNewGenericType(1); //Contains a new GenericClassSub1;
    var item2 = factory.GetNewGenericType(2); //Contains a new GenericClassSub2;
    var item3 = factory.GetNewGenericType(3); //Contains a new GenericClassSub3;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM