單例模式

1.什麼是單例模式?數據庫

  單例模式就是保證進程中某一個類只有一個實例。函數

2.爲何要有單列模式?spa

  1)構造對象須要耗時好資源 線程

  2)一個對象可能會在多個地方存在 日誌

  3)想避免對象重複構造code

3.怎麼保證只有一個實例?對象

  1)私有化構造函數,避免別人去實例化對象blog

  2)在類裏面提供一個公開的靜態方法,在靜態方法裏面實例化對象進程

  3)初始化一個公開的靜態字段用於返回實例化的對象,保證全局只有一個對象資源

4.應對一些特殊狀況:好比數據庫鏈接池,全局惟一號碼生成器

5.單例的兩種模式

  1)經典模式:就是咱們常常說的雙IF+鎖(Lock)

    

 1 public class Singleton
 2     {
 3         private static Singleton _singleton = null;
 4         private static object _isLock = new object();
 5 
 6         public static Singleton CreateIntance()
 7         {
 8             //對象_singleton已經被初始化了就不要進入鎖等待了
 9             if (_singleton == null)
10             {
11                 //加鎖,保證任意時刻只有一個線程進入lock範圍
12                 lock (_isLock)
13                 {
14                     Thread.Sleep(3000);
15                     Console.WriteLine("等待鎖2s以後在繼續...");
16                     //對象是否已經建立
17                     if (_singleton == null)
18                     {
19                         _singleton = new Singleton();
20                     }
21                 }
22             }
23             return _singleton;
24         }
25 }

 

  2)飢餓模式

  

 1 public class Hungry
 2     {
 3         private static Hungry _singleton = null;
 4         private static Hungry _singleton1 = new Hungry();
 5         /// <summary>
 6         /// 靜態構造函數:由CLR保證,程序第一次使用這個類型前被調用一次,而且只調用一次
 7         /// 檢測,初始化,
 8         /// 寫日誌功能的文件夾檢測
 9         /// XML配置文件
10         /// </summary>
11         static Hungry()
12         {
13             _singleton = new Hungry();
14             Console.WriteLine($"Hungry 被啓用...");
15         }
16 
17         /// <summary>
18         /// 惡漢模式,只要使用這個類就會被調用
19         /// </summary>
20         /// <returns></returns>
21         public static Hungry CreateIntance()
22         {
23             return _singleton;
24         }
25 
26         /// <summary>
27         /// 靜態字段在第一次使用這個類以前,由CLR保證初始化而且只初始化一次(比構造函數還早)
28         /// 惡漢模式,只要使用這個類就會被調用
29         /// </summary>
30         /// <returns></returns>
31         public static Hungry CreateIntance1()
32         {
33             return _singleton1;
34         }
35     }
相關文章
相關標籤/搜索