1. 程式人生 > 資訊 >原日本 LINE 集團員工入職小冰公司:目標為創造 AI 虛擬員工

原日本 LINE 集團員工入職小冰公司:目標為創造 AI 虛擬員工

單例模式是什麼? 保證一個類僅有一個例項,並提供一個訪問它的全域性訪問點,當某些類建立物件記憶體開銷消耗大時可以考慮使用該模式 應用場景: 1)資源的共享 2)資料庫連線池的設計 單例模式分為餓漢式懶漢式 1.餓漢式單例類 -自己被載入時就將自己例項化
 1 /// <summary>
 2 /// 餓漢模式
 3 /// </summary>
 4 public class SingletonTest
 5 {
 6     private static SingletonTest instance=new SingletonTest();
 7 
 8     private SingletonTest() { }
9 10 public static SingletonTest GetInstance() 11 { 12 return instance; 13 } 14 }
C# 靜態初始化
 1 public sealed class SingletonTest
 2 {
 3     private static readonly SingletonTest instance = new SingletonTest();
 4 
 5     private SingletonTest() { }
 6 
 7     public static SingletonTest GetInstance()
8 { 9 return instance; 10 } 11 }
其中關鍵詞sealed,阻止發生派生 2.懶漢式單例類-第一次引用時,才會將自己例項化
 1 //懶漢模式
 2 public class SingletonTest
 3 {
 4     private static SingletonTest instance;
 5 
 6     private SingletonTest() { }
 7 
 8     public static SingletonTest GetInstance()
 9     {
10         if
(instance == null) 11 { 12 instance = new SingletonTest(); 13 } 14 return instance; 15 } 16 }
產生問題:多執行緒下不安全,解決方式:雙重鎖定
 1 public class SingletonTest
 2 {
 3     private static SingletonTest instance;
 4     private static readonly object syncRoot = new object();
 5     private SingletonTest() { }
 6 
 7     public static SingletonTest GetInstance()
 8     {
 9 
10         if (instance == null)
11         {
12             lock (syncRoot)
13             {
14                 if (instance == null)
15                 {
16                     instance = new SingletonTest();
17                 }
18             } 
19         }
20         return instance;    
21     }
22 }
餓漢和懶漢的區別: 餓漢式是類一載入就例項化的物件,要提前佔用資源,懶漢會有多執行緒訪問的問題。通常情況下,餓漢式已滿足需求。 以上,僅用於學習和總結!