public class Singleton
{
// Private static object can access only inside the Emp class.
private static Singleton instance;
// Private empty constructor to restrict end use to deny creating the object.
private Singleton()
{
}
// A public property to access outside of the class to create an object.
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
{
private static volatile MultiThreadSingleton instance;
private static object syncRoot = new Object();
private MultiThreadSingleton()
{
}
public static MultiThreadSingleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new MultiThreadSingleton();
}
}
}
return instance;
}
}
{
// Private static object can access only inside the Emp class.
private static Singleton instance;
// Private empty constructor to restrict end use to deny creating the object.
private Singleton()
{
}
// A public property to access outside of the class to create an object.
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
{
private static volatile MultiThreadSingleton instance;
private static object syncRoot = new Object();
private MultiThreadSingleton()
{
}
public static MultiThreadSingleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new MultiThreadSingleton();
}
}
}
return instance;
}
}
}
//static only
public sealed class SealedSingleton
{
private static readonly SealedSingleton instance = new SealedSingleton();
private SealedSingleton()
{
}
public static SealedSingleton Instance
{
get
{
return instance;
}
}
}
http://msdn.microsoft.com/zh-cn/library/ff650316.aspx
本文详细介绍了单例模式的实现及其在多线程环境下的安全优化,包括私有静态对象、空构造函数、公共静态属性及多线程同步机制。
176

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



