2.C#設計模式系列01_單例模式_Singleton

碧水孤鶩發表於2021-07-21

前言:單例模式個人覺得是比較容易理解,而且面試比較容易遇到,但是在實際生產中要慎用的一種設計模式,以前總覺得很難,系統的瞭解了下,主要有以下幾種寫法

1.雙if + lock 

 1 public class SingletonModel {
 2 
 3         private static SingletonModel instance = null;
 4         private static object singleton_lock = new object();
 5         private SingletonModel() {
 6             Console.WriteLine("建構函式");
 7         }
 8 
 9         //多執行緒測試
10         public static SingletonModel SingletonCreatInstance() {
11             if (instance == null){
12                 lock (singleton_lock){
13                     if (instance == null){
14                         instance = new SingletonModel();
15                     }
16                 }
17             }
18             return instance;
19         }
20     }

 

2.靜態成員變數

  public class SingletonTwo{

        private static SingletonTwo slModel = new SingletonTwo();
        private SingletonTwo() {
            Console.WriteLine("建構函式");
        }

        public static SingletonTwo CreateInstanceTwo{
            get{
                return slModel;
            }
        }
    }

 

3.靜態建構函式

public class SingletonOne {

        //靜態建構函式
        private static SingletonOne slModel =null;
        static SingletonOne(){
            slModel = new SingletonOne();
            Console.WriteLine("建構函式");
        }

        public static  SingletonOne CreateInstance() {
            return slModel;
        }
    }

 

4.Lazy延時載入

public class SingletonThree {
        private static Lazy<SingletonThree> lazyModel = new Lazy<SingletonThree>(() => new SingletonThree());
        private SingletonThree(){
        }

        public static SingletonThree CreatInstance() {
            return lazyModel.Value;
        }
    }
public class SingletonFour{

        private static Lazy<SingletonFour> lazyModel;
        private SingletonFour(){
        }

        static SingletonFour() {
            lazyModel = new Lazy<SingletonFour>(new SingletonFour());
        }

        public static SingletonFour CreatInstance() {
            return lazyModel.Value;
        }
    }

 

總結:

套路無非就是  1.私有建構函式或者靜態建構函式 + 2.私有靜態成員變數  + 3.公共對外的訪問例項方法 ,然後根據實際情況選擇合適的用法

ps:Lazy 用法個人感覺使用靜態成員變數和靜態構造是一樣的

 

相關文章