这个...... 大家应该熟的不能再熟了 虫子就不班门弄斧了
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;
}
直接总结:单例模式确保一个类只有一个实例,并提供一个全局访问点
本文深入探讨单例模式的概念、实现方式及其实现代码,包括静态内部类、枚举和懒汉式三种常见实现方式。
599

被折叠的 条评论
为什么被折叠?



