C#单例模式的几种实现方式

 一、多线程不安全方式实现

 1 public sealed class SingleInstance
 2    {
 3        private static SingleInstance instance;
 4        private SingleInstance() { }
 5        public static SingleInstance Instance
 6        {
 7            get
 8            {
 9                if (null == instance)
10                {
11                    instance = new SingleInstance();
12                }
13                return instance;
14            }
15        }
16    }

 sealed表示SingleInstance不能被继承。其实构造函数私有化已经达到了这个效果,私有的构造函数不能被继承。为了可读性,可以加个sealed。私有化构造函数的另一个作用是让当前类不能被实例化,只能通过成员方法获取到类的实例。

不安全的单例指的是在多线程环境下可能有多个线程同时进入if语句,创建了多次单例对象。

二、安全的单例模式

 1 public sealed class SingleInstance
 2   {
 3       private static volatile SingleInstance instance;
 4       private static readonly object obj = new object();
 5       private SingleInstance() { }
 6       public static SingleInstance Instance
 7       {
 8           get
 9           {
10               if (null == instance)
11               {
12                   lock (obj)
13                   {
14                       if (null == instance)
15                       {
16                           instance = new SingleInstance();
17                       }
18                   }
19  
20               }
21               return instance;
22           }
23       }
24   }

加锁保护,在多线程下可以确保实例值被创建一次。缺点是每次获取单例,都要进行判断,涉及到的锁和解锁比较耗资源。由此引入下一种单例模式的实现方式,采取的是以内存换速度的策略。

三、只读属性式

 1 public sealed class SingleInstance
 2    {
 3        private static readonly SingleInstance instance = new SingleInstance();
 4        private SingleInstance() { }
 5        public static SingleInstance Instance
 6        {
 7            get
 8            {
 9                return instance;
10            }
11        }
12    }

借助readonly属性,Instance只被初始化一次,同样达到了单例的效果。在Main函数执行第一句话之前,Instance其实已经被赋值了,并不是预期的当访问Instance变量时才创建对象。

四、使用Lazy

 1 public sealed class SingleInstance
 2    {
 3        private static readonly Lazy<SingleInstance> instance = new Lazy<SingleInstance>(() => new SingleInstance());
 4        private SingleInstance(){}
 5        public static SingleInstance Instance
 6        {
 7            get
 8            {
 9                return instance.Value;
10            }
11        }
12    }

Lazy默认是线程安全的。MSDN描述如下:

 Will the lazily initialized object be accessed from more than one thread? If so, the Lazy<T> 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<T> 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<T> object that is not thread safe, you must use a constructor that enables you to specify no thread safety.

翻译过来就是:

是否可以从多个线程访问延迟初始化的对象? 如果是这样,Lazy <T>对象可能会在任何线程上创建它。 您可以使用其中一个简单构造函数,其默认行为是创建一个线程安全的Lazy <T>对象,这样无论有多少线程尝试访问它,都只会创建一个延迟实例化对象的实例。 要创建非线程安全的Lazy <T>对象,必须使用能够指定无线程安全性的构造函数。

五、泛型单例

 1 public class Singleton<T>  where T:new()
 2 {
 3     private static  T instance;
 4    
 5     private static readonly object obj=new object();
 6    
 7     private Singleton(){}
 8 
 9     public T GetInstance()
10    {
11      if(instance==null)   
12     {
13       lock(obj)
14        {
15           if(instance==null)
16           {
17               instance=new T();
18           }
19        }
20      }
21     return instance;
22    }  
23  }   

泛型单例模式配合工厂模式使用更佳,可以对任意满足要求的对象实现单例。

部分转载自  https://www.cnblogs.com/lh218/p/4713599.html

原文地址:https://www.cnblogs.com/LagoOrLY/p/10302461.html