设计模式之单件模式
本文介绍了C#下关于单例的三种实现方法。
最普通的一种:
以下是引用片段: using System; public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton Instance { get { if (instance == null) instance = new Singleton(); return instance; } } } |
这种方案在.net下面是线程不
下面是一种在.Net公共语言运行环境下的线程安全单例实现模式:
以下是引用片段: public sealed class Singleton { private static readonly Singleton instance = new Singleton(); private Singleton(){} public static Singleton Instance { get { return instance; } } } |
它是依靠公共语言运行时的
基于此加上
以下是引用片段: public class SingletonProvider where T : new() { SingletonProvider() { } public static T Instance { get { return SingletonCreator.instance; } } class SingletonCreator { static SingletonCreator() { } internal static readonly T instance = new T(); } } |
在此应用下,单例的实例由CLR保证只在首次引用它时才会被创建。
当它不能满足需要时,比如:你需要在
一个线线程安全的单例:
以下是引用片段: using System; public sealed class Singleton { private static volatile Singleton instance; private static object syncRoot = new Object(); private Singleton() {} public static Singleton Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) instance = new Singleton(); } } return instance; } } } |
需要注意的时,这里锁定的是syncRoot,而不是本身,这可以避免产生死锁。
在其它的语言环境中,Double-Checked Locking不一定能正常工作,这是由于编译器本身的