110,535
社区成员
发帖
与我相关
我的任务
分享
public static Singleton GetInstance()
{
if (uniqueInstance == null)
{
lock (locker)
{
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
public class aaa
{
static readonly Dictionary<Type, object> _instances = new Dictionary<Type, object>();
public T GetSingleInstance<T>()
{
object obj;
var type = typeof(T);
// 这里不能做双重Check,Dictionary并不是线程安全的
// if (!_instances.TryGetValue(type, out obj))
{
lock (_instances)
{
if (!_instances.TryGetValue(type, out obj))
{
obj = ClassLoader.CreateInstance(type);
_instances[type] = obj;
}
}
}
return (T) obj;
}
}