實用的泛型Singleton類
來源:互聯網
上載者:User
Singleton模式是最常的設計模式之一,我們會經常寫這類代碼.因其基本原理就是儲存一個靜態對象執行個體,所以我們便能利用泛型寫出一個通用的Singleton類. 代碼很簡單: public class Singleton<T>
...{
static readonly T _t;
static Singleton()
...{
_t = Construct();
}
public static T GetInstance()
...{
return _t;
}
private static T Construct()
...{
Type type = typeof(T);
ConstructorInfo ctor;
ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, new Type[0], new ParameterModifier[0]);
System.Diagnostics.Debug.Assert(ctor != null, "Error in ENLS.Basic.Singleton.Construct().");
return (T)ctor.Invoke(new object[0]);
}
}因為特化的泛型類是不同的類型,Singleton<Tuple<int>>和Singleton<Tuple<int,long>>不同,所以這兩個類中的_t是不同的靜態執行個體.然後在Construct方法中通過反射調用共有或私人的預設構造參數來建立新執行個體.為什麼會有public的建構函式呢,這是為了使用NullObject模式.比如為了方便我要給Tuple基類添加一個方法用來的到Null 物件 public static Tuple GetNullInstance<_Tuple>() where _Tuple: Tuple
{
return Singleton<_Tuple>.GetInstance();
}有了這個Null 物件我就可以更簡單的使用前面文章中介紹的遍曆控制項的函數.public IEnumerable<Control> Iterator<_Tuple>(Control baseCtl) where _Tuple : Tuple
...{
Tuple tuple = Tuple.GetNullInstance<_Tuple>();
foreach(Control c in baseCtl.Controls)
...{
if (!tuple.HasType(c))
...{
foreach (Control c1 in Iterator<_Tuple>(c))
yield return c1;
}
else
yield return c;
}
}這樣就可以很方便的調用了foreach (Control c in this.Iterator<Tuple<TextBox, TreeView, CheckBox>>(this))
MessageBox.Show(c.Name);