设计模式——Unity通用泛型单例(普通型和继承自MonoBehaviour)

单例模式是设计模式中最为常见的,不多解释了。但应该尽量避免使用,一般全局管理类才使用单例。

 

普通泛型单例:

 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的泛型单例:

 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)的唯一实例了。

posted @ 2019-07-17 20:59  汐夜  阅读(3502)  评论(0编辑  收藏  举报