用双锁检查Singleton设计模式 [英] Singleton design pattern with double-check lock
本文介绍了用双锁检查Singleton设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想想你有下面的代码:结果
1.为什么我们使用双重检查锁定,为什么单锁不够好,请提供详细的例子结果
2.什么。与此实施的主要缺点?我应该怎么证明呢?结果
感谢。
公共密封类SomeSingleton5
$ { b $ b私人静态SomeSingleton5 s_Instance = NULL;
私有静态对象s_LockObj =新的对象();
私人SomeSingleton5(){}
公共静态SomeSingleton5实例
{
得到
{
如果(s_Instance == NULL)
{
锁(s_LockObj)
{
如果(s_Instance == NULL)
{
s_Instance =新SomeSingleton5();
}
}
}
返回s_Instance;
}
}
}
解决方案
我觉得单例类的最好的实现是由乔恩斯基特
提供。
公共密封类辛格尔顿
{
私人静态只读Singleton实例=新辛格尔顿();
公共静态Singleton实例{{返回实例; }}
静态辛格尔顿(){}
私人辛格尔顿(){}
}
块引用>Consider you have the following code:
1. Why do we use double check lock, why single lock is not good enough, please provide detailed example.
2. What are the main drawbacks with this implementation? and how should I prove it?
Thanks.public sealed class SomeSingleton5 { private static SomeSingleton5 s_Instance = null; private static object s_LockObj = new Object(); private SomeSingleton5() { } public static SomeSingleton5 Instance { get { if (s_Instance == null) { lock (s_LockObj) { if (s_Instance == null) { s_Instance = new SomeSingleton5(); } } } return s_Instance; } } }
解决方案I think the best implementation of singleton class is provided by
Jon Skeet
.public sealed class Singleton { private static readonly Singleton instance = new Singleton(); public static Singleton Instance { get { return instance; } } static Singleton() {} private Singleton() {} }
这篇关于用双锁检查Singleton设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文