色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

一個簡單的 Generic Factory 類

  簡單的工廠類的一個使用場景是, 假設(shè)有一個基類 BaseClass, 和一系列的子類 A, B, C, 工廠類根據(jù)某個參數(shù),例如字符串 “A”, “B”, “C” 創(chuàng)建出相應(yīng)的子類。 舉例如下:

public class Factory{    public static BaseClass Create(string name)    {        switch (name)        {            case "A": return new A();            case "B": return new B();            case "C": return new C();            default: throw new ArgumentException("Wrong Name");        }    }}

  這里的一個問題是, 當(dāng)子類增加或減少時, Factory 類 需要相應(yīng)的改動。 有沒有辦法可以只是改動子類本身, 而不用修改Factory類呢, 當(dāng)然有,這里我舉一個簡單的實(shí)現(xiàn)。

  基本思想是在每個子類上附加一個 Attribute, 定義如下:

[AttributeUsage(AttributeTargets.Class)]public class FactoryKeyAttribute : Attribute{    public object Key { get; set; }}

  假設(shè)我們有基類和子類實(shí)現(xiàn)如下

public abstract class BaseClass {}[FactoryKey(Key = "Standard")]public class Standard : BaseClass {}[FactoryKey(Key = "Enterprise")]public class Enterprise : BaseClass {}[FactoryKey(Key = "Lite")]public class Lite : BaseClass {}

 

  假設(shè)這些類都在同一個 Assembly中 (對于不在同一個Assembly的,實(shí)現(xiàn)會稍微復(fù)雜些)工廠類需要預(yù)先加載 Key => Type 的Mapping, 然后根據(jù)Key創(chuàng)建不同的實(shí)例, 實(shí)現(xiàn)如下:

public static class Factory<TKey, TBaseClass>{    private static readonly IDictionary<TKey, Type> TypeDict = Init();    private static IDictionary<TKey, Type> Init()    {        var dict = from type in Assembly.GetExecutingAssembly().GetTypes()                   let key = (FactoryKeyAttribute)Attribute.GetCustomAttribute(type, typeof(FactoryK
eyAttribute
)) where key != null && type.IsSubclassOf(typeof(TBaseClass)) select new { Key = key, Value = type }; return dict.ToDictionary(kvp => (TKey)kvp.Key.Key, kvp => kvp.Value); } public static TBaseClass CreateInstance(TKey key) { Type type; if (TypeDict.TryGetValue(key, out type)) { return (TBaseClass)Activator.CreateInstance(type); } throw new ArgumentException("Incorrect Key!"); }}

  使用方法也很簡單:

BaseClass s = Factory<string, BaseClass>.CreateInstance("Standard");BaseClass l = Factory<string, BaseClass>.CreateInstance("Lite");BaseClass e = Factory<string, BaseClass>.CreateInstance("Enterprise");

 

  對于其他類型的Key,比如 Enum, 或其他類型的基類, 改變Factory 的類型參數(shù)即可。

NET技術(shù)一個簡單的 Generic Factory 類,轉(zhuǎn)載需保留來源!

鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。

主站蜘蛛池模板: 开远市| 汤阴县| 平果县| 昌江| 新郑市| 隆化县| 航空| 清丰县| 遵义市| 措勤县| 阜康市| 泽普县| 巴南区| 阳东县| 沙湾县| 东兴市| 内丘县| 海丰县| 伊宁市| 上犹县| 射洪县| 平原县| 山东省| 达州市| 天等县| 那曲县| 沙坪坝区| 襄垣县| 霸州市| 襄垣县| 河池市| 丰县| 呼和浩特市| 沂源县| 潮安县| 新晃| 通城县| 潞西市| 伊吾县| 安图县| 汶川县|