設計模式——Unity通用泛型單例(普通型和繼承自MonoBehaviour)

單例模式是設計模式中最爲常見的,很少解釋了。但應該儘可能避免使用,通常全局管理類才使用單例。設計模式

 

普通泛型單例:ide

 1 public abstract class Singleton<T> where T : class, new()
 2 {
 3     private static T instance = null;
 4 
 5     private static readonly object locker = new object();
 6 
 7     public static T Instance
 8     {
 9         get
10         {
11             lock (locker)
12             {
13                 if (instance == null)
14                     instance = new T();
15                 return instance;
16             }
17         }
18     }
19 }

 

繼承MonoBehaviour的泛型單例:ui

 1 using UnityEngine;
 2 
 3 public abstract class MonoSingleton <T>: MonoBehaviour where T:MonoBehaviour
 4 {
 5     private static T instance = null;
 6 
 7     private static readonly object locker = new object();
 8 
 9     private static bool bAppQuitting;
10 
11     public static T Instance
12     {
13         get
14         {
15             if (bAppQuitting)
16             {
17                 instance = null;
18                 return instance;
19             }
20 
21             lock (locker)
22             {
23                 if (instance == null)
24                 {
25                     instance = FindObjectOfType<T>();
26                     if (FindObjectsOfType<T>().Length > 1)
27                     {
28                         Debug.LogError("不該該存在多個單例!");
29                         return instance;
30                     }
31 
32                     if (instance == null)
33                     {
34                         var singleton = new GameObject();
35                         instance = singleton.AddComponent<T>();
36                         singleton.name = "(singleton)" + typeof(T);
37                         singleton.hideFlags = HideFlags.None;
38                         DontDestroyOnLoad(singleton);
39                     }
40                     else
41                         DontDestroyOnLoad(instance.gameObject);
42                 }
43                 instance.hideFlags = HideFlags.None;
44                 return instance;
45             }
46         }
47     }
48 
49     private void Awake()
50     {
51         bAppQuitting = false;
52     }
53 
54     private void OnDestroy()
55     {
56         bAppQuitting = true;
57     }
58 }

 

使用方法直接用類去繼承這兩個抽象單例便可,使用T.Instance就能夠直接取得該類(T)的惟一實例了。spa

相關文章
相關標籤/搜索