從今天開始正式學習C#設計模式:
第一章: Singleton模式(單列模式)
該模式爲創建形模式,(Creational)
Intent:
確保在系統中只有一個實例,並提供一個該實例的全局訪問點(這個責任應該是類設計者的,而非使用者責任)
單線程情況下:
public class Thread
{
private static Thread _Instance = null;
private Thread()
{
}
public static Thread Instance
{
get
{
if (_Instance != null)
{
_Instance = new Thread();
}
return _Instance;
}
}
}
{
private static Thread _Instance = null;
private Thread()
{
}
public static Thread Instance
{
get
{
if (_Instance != null)
{
_Instance = new Thread();
}
return _Instance;
}
}
}
多線程情況下:
public class MultiThread
{
private static volatile MultiThread _Instance = null;
private static object lockHelper = new object();
private MultiThread()
{ }
public static MultiThread Intance
{
get
{
if (_Instance != null)
{
lock (lockHelper)
{
if (_Instance != null)
{
_Instance = new MultiThread();
}
}
}
return _Instance();
}
}
}
{
private static volatile MultiThread _Instance = null;
private static object lockHelper = new object();
private MultiThread()
{ }
public static MultiThread Intance
{
get
{
if (_Instance != null)
{
lock (lockHelper)
{
if (_Instance != null)
{
_Instance = new MultiThread();
}
}
}
return _Instance();
}
}
}
另外一種比較好的方法(但該方法不支持在創建對象時使用參數)
public class AnotherMethod
{
public static readonly AnotherMethod Intance = new AnotherMethod();
private AnotherMethod()
{ }
}
{
public static readonly AnotherMethod Intance = new AnotherMethod();
private AnotherMethod()
{ }
}
注意:
C#中,靜態構造器只在靜態屬性和方法之前執行,因爲該方法是RunTime調用,所以無法傳參.
擴展:
1,將只能有1個實例,擴展到只能有N個實例子,例如對象池的實現
2,將new 構造器的調用轉移到其他類中,例如多個類協同工作環境中,某個局部環境只需要擁有某個類的一個實例。