站在类的设计者的角度,强制使一个类只能有一个实例,而不是站在类的使用者角度。
要点:
1.singleton不要实现ICloneable,避免出现多个实例,与singleton冲突
2.singleton不要支持序列化,如上同理。
3.不要实现在多现程环境中.
单件模形初形
public
class
Singleton
{
private static Singleton instance = null;
private Singleton() { }
public static Singleton Instance
{
get
{
//惰性初 始化
if (instance == null)
{
instance = new Singleton();
}
}
return instance;
}
}
单件模形与多线程
{
private static Singleton instance = null;
private Singleton() { }
public static Singleton Instance
{
get
{
//惰性初 始化
if (instance == null)
{
instance = new Singleton();
}
}
return instance;
}
}
public
class
Singleton
{
//volatile 关键字的作用是 防止编辑器在编辑时对 它所修饰的对象
//进行微调,达到真正锁定多线程的目的
private static volatile Singleton instance = null;
//一个辅助对象,用来作线程锁定
private static object lockHelper = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
//双检查
if (instance == null)
{
//锁定,防止多线程访问产生对个对象
lock (lockHelper)
{
if(instance == null)
{
instance = new Singleton();
}
}
return instance;
}
}
}
}
{
//volatile 关键字的作用是 防止编辑器在编辑时对 它所修饰的对象
//进行微调,达到真正锁定多线程的目的
private static volatile Singleton instance = null;
//一个辅助对象,用来作线程锁定
private static object lockHelper = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
//双检查
if (instance == null)
{
//锁定,防止多线程访问产生对个对象
lock (lockHelper)
{
if(instance == null)
{
instance = new Singleton();
}
}
return instance;
}
}
}
}
用static readyonly 表示,缺点是不支持参数传递
public
class
Singleton
{
public static readyonly Singleton sl = new Singleton();
private Singleton(){}
}
/**/ ///
上面的代码与下面的等效
/**/ //
public class Singleton
{
public static readyonly Singleton s1;
//静态的实例构造器
static Singleton()
{
s1 = new Singleton();
}
}
/**/ ///
.net机制自动为static对象进行了多线程处理.所以可以省略
/**/ ///
{
public static readyonly Singleton sl = new Singleton();
private Singleton(){}
}
/**/ ///
上面的代码与下面的等效
/**/ //
public class Singleton
{
public static readyonly Singleton s1;
//静态的实例构造器
static Singleton()
{
s1 = new Singleton();
}
}
/**/ ///
.net机制自动为static对象进行了多线程处理.所以可以省略
/**/ ///