概述:
单例模式又称单件模式,模式用来创建独一无二的只有一个实例的对象,并提供一个全局访问点。
经典的单例模式实现:
1 public class Singleton
2 {
3 private static Singleton instance = null;
4
5 public static Singleton Instance
6 {
7 get
8 {
9 if (instance == null)
10 {
11
12 instance = new Singleton();
13 }
14 return instance;
15 }
16 }
3 private static Singleton instance = null;
4
5 public static Singleton Instance
6 {
7 get
8 {
9 if (instance == null)
10 {
11
12 instance = new Singleton();
13 }
14 return instance;
15 }
16 }
17 }
这种方式存在的缺点是线程不安全,当出现多线程情况的时候,有多可能出现多个实例。
解决方法是采用lock来限制只能单个线程进入:
public class Singleton
{
private static Singleton instance = null;
private static readonly Object locker = new Object();
public static Singleton Instance
{
get
{
lock (locker)
{
if (instance == null)
{
instance = new Singleton();
}
}
return instance;
}
}
}
private static Singleton instance = null;
private static readonly Object locker = new Object();
public static Singleton Instance
{
get
{
lock (locker)
{
if (instance == null)
{
instance = new Singleton();
}
}
return instance;
}
}
}
通过这样实现了线程安全,不过如果每一次调用都需要去lock一次然后判断是实例是否为null开销很多,我们可以通过double check 方式减少不不要的开销。方法如下:
public class Singleton
{
private static Singleton instance = null;
private static readonly Object locker = new Object();
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (locker)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
{
private static Singleton instance = null;
private static readonly Object locker = new Object();
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (locker)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
通过double check 解决线程并发问题,同时解决了每次实例的时候都会进行的线程加锁损耗。
单例模式适合于只能有一个实例而且客户可以从全局的访问点访问它时
应用场景有:缓存,多线程并发中需要单个实例,线程池等
原文地址:http://www.cnblogs.com/xoray007/archive/2010/10/22/1857912.html