動機(Motivation)
一些特殊的類 只存在一個實例(確保他們的邏輯正確性)
這個應該是類設計者的責任,而不是使用者的責任。
如何繞過常規的構造器?提供一種機制保證一個類只有一個實例?
意圖(Intent)
確保一個類只有一個實例。
單線程Singleton模式實現
class Singleton
{
private static Singleton instance;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if(instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
構造器可以設置爲protected以允許子類派生
不要支持ICloneable接口
不要支持序列化
缺點是,不能應對多線程的情況
這個模式,我們只考慮了對象的創建而沒有考慮對象的銷燬
多線程實現
class MulThreadSingleton
{
private static volatile MulThreadSingleton instance = null;
private static Object lockHelper = new Object();
private MulThreadSingleton()
{
}
public static MulThreadSingleton Instance
{
get
{
if(instance == null)
{
lock(lockHelper)
{
if(instance == null)
{
instance = new MulThreadSingleton();
}
}
}
return instance;
}
}
}
使用靜態構造器