結合項目實例 回顧傳統設計模式(五)單例模式
2011-10-04 14:05 熬夜的蟲子 閱讀(545) 評論(0) 收藏 舉報這個...... 大家應該熟的不能再熟了 蟲子就不班門弄斧了
private static object LockKey = new object();
private static T _Instance;
public static T GetInstance()
{
return GetInstance(null);
}
public static T GetInstance(Func<T> onCreateInstance)
{
if (_Instance == null)
{
lock (LockKey)
{
if (_Instance == null)
{
try
{
if (onCreateInstance == null)
_Instance = new T();
else
_Instance = onCreateInstance();
}
catch
{
_Instance = default(T);
}
}
}
}
return _Instance;
}
public static T GetInstance(object lockKey, T instance, Func<T> onCreateInstance)
{
if (instance == null)
{
if (lockKey == null)
lockKey = LockKey;
lock (lockKey)
{
if (instance == null)
{
try
{
if (onCreateInstance == null)
instance = new T();
else
instance = onCreateInstance();
}
catch
{
instance = default(T);
}
}
}
}
return instance;
}
private static T _Instance;
public static T GetInstance()
{
return GetInstance(null);
}
public static T GetInstance(Func<T> onCreateInstance)
{
if (_Instance == null)
{
lock (LockKey)
{
if (_Instance == null)
{
try
{
if (onCreateInstance == null)
_Instance = new T();
else
_Instance = onCreateInstance();
}
catch
{
_Instance = default(T);
}
}
}
}
return _Instance;
}
public static T GetInstance(object lockKey, T instance, Func<T> onCreateInstance)
{
if (instance == null)
{
if (lockKey == null)
lockKey = LockKey;
lock (lockKey)
{
if (instance == null)
{
try
{
if (onCreateInstance == null)
instance = new T();
else
instance = onCreateInstance();
}
catch
{
instance = default(T);
}
}
}
}
return instance;
}
直接總結:單例模式確保一個類只有一個實例,并提供一個全局訪問點
![]() |
原創作品允許轉載,轉載時請務必以超鏈接形式標明文章原始出處以及作者信息。 作者:熬夜的蟲子 點擊查看:博文索引 |

浙公網安備 33010602011771號