保证一个类仅有一个实例,并提供一个该实例的全局访问点。



//不能完全支持多线程
 public class Singleton
 {
  private static Singleton singleton;
  int x;

  private Singleton(int x)
  {
   this.x = x;
  }

  public static Singleton GetSingleton(int x)
  {
   if(singleton == null)
   {
    //在if之后与本句之前可能线程不安全
    singleton = new Singleton(x);
   }

   return(singleton);
  }

  public string GetValue()
  {
   ++x;
   return(x.ToString());
  }
 }
 //支持多线程
 public class Singleton
 {
  //volatile的设置使C#不允许做代码调整,以使程序完全支持多线程
  private static volatile Singleton singleton;
  private static object lockHelper = new object();
  int x;

  private Singleton(int x)
  {
   this.x = x;
  }

  public static Singleton GetSingleton(int x)
  {
   if(singleton == null)
   {
    lock(lockHelper)
    {
     if(singleton == null)
     {
      singleton = new Singleton(x);
     }
    }
   }

   return(singleton);
  }

  public string GetValue()
  {
   ++x;
   return(x.ToString());
  }
 }

 //支持多线程
 public class Singleton
 {
  public static readonly Singleton singleton = new Singleton();
  int x;

  private Singleton()
  {
   x = 0;
  }

  public int X
  {
   get
   {
    return(this.x);
   }
   set
   {
    this.x = value;
   }
  }

  public string GetValue()
  {
   ++x;
   return(x.ToString());
  }
 }

相关文章:

  • 2021-09-22
  • 2021-05-23
  • 2021-07-17
  • 2022-12-23
  • 2021-07-21
  • 2022-12-23
  • 2021-07-23
  • 2022-12-23
猜你喜欢
  • 2021-12-13
  • 2021-10-05
  • 2022-02-18
  • 2022-12-23
  • 2021-07-27
  • 2022-01-03
相关资源
相似解决方案