一、多线程不安全方式实现
1 public sealed classSingleInstance2 {3 private staticSingleInstance instance;4 privateSingleInstance() { }5 public staticSingleInstance Instance6 {7 get
8 {9 if (null ==instance)10 {11 instance = newSingleInstance();12 }13 returninstance;14 }15 }16 }
sealed表示SingleInstance不能被继承。其实构造函数私有化已经达到了这个效果,私有的构造函数不能被继承。为了可读性,可以加个sealed。私有化构造函数的另一个作用是让当前类不能被实例化,只能通过成员方法获取到类的实例。
不安全的单例指的是在多线程环境下可能有多个线程同时进入if语句,创建了多次单例对象。
二、安全的单例模式
1 public sealed classSingleInstance2 {3 private static volatileSingleInstance instance;4 private static readonly object obj = new object();5 privateSingleInstance() { }6 public staticSingleInstance Instance7 {8 get
9 {10 if (null ==instance)11 {12 lock(obj)13 {14 if (null ==instance)15 {16 instance = newSingleInstance();17 }18 }19
20 }21 returninstance;22 }23 }24 }
加锁保护,在多线程下可以确保实例值被创建一次。缺点是每次获取单例,都要进行判断,涉及到的锁和解锁比较耗资源。由此引入下一种单例模式的实现方式,采取的是以内存换速度的策略。
三、只读属性式
1 public sealed classSingleInstance2 {3 private static readonly SingleInstance instance = newSingleInstance();4 privateSingleInstance() { }5 public staticSingleInstance Instance6 {7 get
8 {9 returninstance;10 }11 }12 }
借助readonly属性,Instance只被初始化一次,同样达到了单例的效果。在Main函数执行第一句话之前,Instance其实已经被赋值了,并不是预期的当访问Instance变量时才创建对象。
四、使用Lazy
1 public sealed classSingleInstance2 {3 private static readonly Lazy instance = new Lazy(() => newSingleInstance());4 privateSingleInstance(){}5 public staticSingleInstance Instance6 {7 get
8 {9 returninstance.Value;10 }11 }12 }
Lazy默认是线程安全的。MSDN描述如下:
Will the lazily initialized object be accessed from more than one thread? If so, the Lazy object might create it on any thread. You can use one of the simple constructors whose default behavior is to create a thread-safe Lazy object, so that only one instance of the lazily instantiated object is created no matter how many threads try to access it. To create a Lazy object that is not thread safe, you must use a constructor that enables you to specify no thread safety.
翻译过来就是:
是否可以从多个线程访问延迟初始化的对象? 如果是这样,Lazy 对象可能会在任何线程上创建它。 您可以使用其中一个简单构造函数,其默认行为是创建一个线程安全的Lazy 对象,这样无论有多少线程尝试访问它,都只会创建一个延迟实例化对象的实例。 要创建非线程安全的Lazy 对象,必须使用能够指定无线程安全性的构造函数。
五、泛型单例
1 public class Singleton where T:new()2 {3 private staticT instance;4
5 private static readonly object obj=new object();6
7 privateSingleton(){}8
9 publicT GetInstance()10 {11 if(instance==null)12 {13 lock(obj)14 {15 if(instance==null)16 {17 instance=newT();18 }19 }20 }21 returninstance;22 }23 }
泛型单例模式配合工厂模式使用更佳,可以对任意满足要求的对象实现单例。