1.简单实现
这种方式的实现对于线程来说并不是安全的,因为在多线程的环境下有可能得到Singleton类的多个实例
public sealed class Singleton
{
//静态字段
static Singleton instance = null;
//私有构造函数
private Singleton()
{
}
//静态属性
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
2.线程安全{
//静态字段
static Singleton instance = null;
//私有构造函数
private Singleton()
{
}
//静态属性
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
在同一个时刻加了锁的那部分程序只有一个线程可以进入。这种情况下,对象实例由最先进入的那个线程创建,后来的线程在进入时(instence == null)为假,不会再去创建对象实例了。但是这种实现方式增加了额外的开销,损失了性能。
public sealed class Singleton
{
//静态字段
static Singleton instance = null;
//静态只读锁
static readonly object padlock = new object();
//私有构造函数
private Singleton()
{
}
//静态属性
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
3.双重锁定{
//静态字段
static Singleton instance = null;
//静态只读锁
static readonly object padlock = new object();
//私有构造函数
private Singleton()
{
}
//静态属性
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
public sealed class Singleton
{
static Singleton instance = null;
static readonly object padlock = new object();
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
{
static Singleton instance = null;
static readonly object padlock = new object();
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
要点
• Singleton模式中的实例构造器可以设置为protected以允许子类派生。
• Singleton模式一般不要支持ICloneable接口,因为这可能会导致多个对象实例,与Singleton模式的初衷违背。
• Singleton模式一般不要支持序列化,因为这也有可能导致多个对象实例,同样与Singleton模式的初衷违背。
• Singletom模式只考虑到了对象创建的管理,没有考虑对象销毁的管理。就支持垃圾回收的平台和对象的开销来
讲,我们一般没有必要对其销毁进行特殊的管理。
• 不能应对多线程环境:在多线程环境下,使用Singleton模式仍然有可能得到Singleton类的多个实例对象。
浙公网安备 33010602011771号