C#单例介绍三种方法

Posted on 2018-08-09 13:52  yacbo  阅读(179)  评论(0编辑  收藏  举报

第一种:双if + lock

 

public class Singleton
{
  private static Singleton _Singleton = null;
  private static object Singleton_Lock = new object();
  public static Singleton CreateInstance()
  {
       if(_Singleton == null)  //双if+lock
        {
            lock (Singleton_Lock)
            {
                Console.WriteLine("路过……");
                 if(_Singleton == null)
                 {
                    Console.WriteLine("被创建……");
                     _Singleton = new Singleton();
                 }
            }
        }       
  } 
}
//测试:
TaskFactory taskFactory = new TaskFactory();
List<Task> taskList = new List<Task>();
for(int i=0;i<5;i++)
{
   taskList.Add(taskFactory.StartNew( ()=>{ Singleton singleton = Singleton.CreateInstance();}));
}

  

第二种:利用静态变量实现单例模式

public class SingletonThird
{
       private static SingletonThird _SingletonThird = new SingletonThird();
       public static SingletonThird CreateInstance()
       {
            return _SingletonThird;
       }
}

  

第三种:利用静态构造函数实现单例模式

public class SingletonSecond
{
    private static SingletonSecond _SingletonSecond = null;
    static SingletonSecond()
    {
        _SingletonSecond = new SingletonSecond();
    }  
    public static SingletonSecond CreateInstance()
    {
          return _SingletonSecond;
    }
}

 

Copyright © 2024 yacbo
Powered by .NET 9.0 on Kubernetes