怎么在c#中实现单例类

  介绍

今天就跟大家聊聊有关怎么在c#中实现单例类,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

<强>实现1:懒汉式、线程不安全

该实现没有额外开销,不要求线程安全的情况下可以使用:

public  class  Singleton1   {   private 才能static  Singleton1  instance =,空;   private 才能;Singleton1 (), {,}      public 才能;static  Singleton1 实例   {才能   ,才能得到   ,,,{   ,,,,,if  (instance ==, null)   ,,,,,{   ,,,,,,,instance =, new  Singleton1 ();   ,,,,,}   ,,,,,return 实例;   ,,,}   ,,}   }

<>强实现2:懒汉式、线程安全

由于每次访问单例类实例都会加锁,而加锁是一个非常耗时的操作,故不推荐使用:

public  class  Singleton2   {   private 才能readonly  static  object  lockObj =, new 对象();   private 才能static  Singleton2  instance =,空;   private 才能;Singleton2 (), {,}      public 才能;static  Singleton2 实例   {才能   ,才能得到   ,,,{   ,,,,,锁(lockObj)   ,,,,,{   ,,,,,,,if  (instance ==, null)   ,,,,,,,{   ,,,,,,,,,instance =, new  Singleton2 ();   ,,,,,,,}   ,,,,,}   ,,,,,return 实例;   ,,,}   ,,}   }

<>强实现3:饿汉式、线程安全

写法简单,线程安全,但构造时机不是由程序员掌控的:

public  class  Singleton3   {   private 才能static  Singleton3  instance =, new  Singleton3 ();   private 才能;Singleton3 (), {,}   public 才能static  Singleton3  Instance  {, get  {, return 实例,},}      public 才能;static  void 测试()   {才能   ,,,Console.WriteLine (“test");   ,,}   }

当。net运行时发现第一次使用Singleton3时会创建单例的实例,而不是在第一次调用Singleton3。实例属性时创建,如进行以下操作:

Singleton3.Test ();

<强>实现4:懒汉式,双重校验锁

在实现2的基础上进行改进,只在第一次创建实例时加锁,提高访问性能:

public  class  Singleton4   {   private 才能readonly  static  object  lockObj =, new 对象();   private 才能static  Singleton4  instance =,空;   private 才能;Singleton4 (), {,}      public 才能;static  Singleton4 实例   {才能   ,才能得到   ,,,{   ,,,,,if  (instance ==, null)   ,,,,,{   ,,,,,,,lock  (lockObj)   ,,,,,,,{   ,,,,,,,,,if  (instance ==, null)   ,,,,,,,,,{   ,,,,,,,,,,,instance =, new  Singleton4 ();   ,,,,,,,,,}   ,,,,,,,}   ,,,,,}   ,,,,,return 实例;   ,,,}   ,,}   }

<>强实现5:懒汉式,内部类

在方法3的基础上进行改进,确保只有访问Singleton5。实例属性时才会构造实例:

public  class  Singleton5   {   class 才能;Nested    {才能   ,,,internal  static  readonly  Singleton5  instance =, new  Singleton5 ();   ,,}   private 才能;Singleton5 (), {,}   public 才能static  Singleton5  Instance  {, get  {, return  Nested.instance,},}   }

实现单例基类

通过单例基类,我们可以简单的通过继承创建一个单例类,实现代码复用:

//,由于单例基类不能实例化,故设计为抽象类   public  abstract  class  Singleton< T>, where  T :类   {//才能,这里采用实现5的方案,实际可采用上述任意一种方案   ,class 嵌套   {才能   ,,,//,创建模板类实例,参数2设为真表示支持私有构造函数   ,,,internal  static  readonly  T  instance =, Activator.CreateInstance (typeof (T),真的),as  T;   ,,}   private 才能static  T  instance =,空;   null   null   null   null   null   null

怎么在c#中实现单例类