单例是我们最常用的设计模式,尤其是在Unity项目的开发中,几乎每个项目都会用到单例模式。

QFramework包含的单例实现

网址:SingletonKit/SingletonKit.cs at main · liangxiegame/SingletonKit (github.com)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/****************************************************************************
* Copyright (c) 2017 ~ 2021 liangxie MIT License
*
* https://github.com/liangxiegame/SingletonKit
****************************************************************************/

using System;
using System.Reflection;
using UnityEngine;

namespace QFramework
{
/// <summary>
/// 单例接口
/// </summary>
public interface ISingleton
{
/// <summary>
/// 单例初始化(继承当前接口的类都需要实现该方法)
/// </summary>
void OnSingletonInit();
}

/// <summary>
/// 普通类的单例
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Singleton<T> : ISingleton where T : Singleton<T>
{
/// <summary>
/// 静态实例
/// </summary>
protected static T mInstance;

/// <summary>
/// 标签锁:确保当一个线程位于代码的临界区时,另一个线程不进入临界区。
/// 如果其他线程试图进入锁定的代码,则它将一直等待(即被阻止),直到该对象被释放
/// </summary>
static object mLock = new object();

/// <summary>
/// 静态属性
/// </summary>
public static T Instance
{
get
{
lock (mLock)
{
if (mInstance == null)
{
mInstance = SingletonCreator.CreateSingleton<T>();
}
}

return mInstance;
}
}

/// <summary>
/// 资源释放
/// </summary>
public virtual void Dispose()
{
mInstance = null;
}

/// <summary>
/// 单例初始化方法
/// </summary>
public virtual void OnSingletonInit()
{
}
}

/// <summary>
/// 属性单例类
/// </summary>
/// <typeparam name="T"></typeparam>
public static class SingletonProperty<T> where T : class, ISingleton
{
/// <summary>
/// 静态实例
/// </summary>
private static T mInstance;

/// <summary>
/// 标签锁
/// </summary>
private static readonly object mLock = new object();

/// <summary>
/// 静态属性
/// </summary>
public static T Instance
{
get
{
lock (mLock)
{
if (mInstance == null)
{
mInstance = SingletonCreator.CreateSingleton<T>();
}
}

return mInstance;
}
}

/// <summary>
/// 资源释放
/// </summary>
public static void Dispose()
{
mInstance = null;
}
}

/// <summary>
/// 普通单例创建类
/// </summary>
internal static class SingletonCreator
{
static T CreateNonPublicConstructorObject<T>() where T : class
{
var type = typeof(T);
// 获取私有构造函数
var constructorInfos = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);

// 获取无参构造函数
var ctor = Array.Find(constructorInfos, c => c.GetParameters().Length == 0);

if (ctor == null)
{
throw new Exception("Non-Public Constructor() not found! in " + type);
}

return ctor.Invoke(null) as T;
}

public static T CreateSingleton<T>() where T : class, ISingleton
{
var type = typeof(T);
var monoBehaviourType = typeof(MonoBehaviour);

if (monoBehaviourType.IsAssignableFrom(type))
{
return CreateMonoSingleton<T>();
}
else
{
var instance = CreateNonPublicConstructorObject<T>();
instance.OnSingletonInit();
return instance;
}
}


/// <summary>
/// 单元测试模式 标签
/// </summary>
public static bool IsUnitTestMode { get; set; }

/// <summary>
/// 查找Obj(一个嵌套查找Obj的过程)
/// </summary>
/// <param name="root">父节点</param>
/// <param name="subPath">拆分后的路径节点</param>
/// <param name="index">下标</param>
/// <param name="build">true</param>
/// <param name="dontDestroy">不要销毁 标签</param>
/// <returns></returns>
private static GameObject FindGameObject(GameObject root, string[] subPath, int index, bool build,
bool dontDestroy)
{
GameObject client = null;

if (root == null)
{
client = GameObject.Find(subPath[index]);
}
else
{
var child = root.transform.Find(subPath[index]);
if (child != null)
{
client = child.gameObject;
}
}

if (client == null)
{
if (build)
{
client = new GameObject(subPath[index]);
if (root != null)
{
client.transform.SetParent(root.transform);
}

if (dontDestroy && index == 0 && !IsUnitTestMode)
{
GameObject.DontDestroyOnLoad(client);
}
}
}

if (client == null)
{
return null;
}

return ++index == subPath.Length ? client : FindGameObject(client, subPath, index, build, dontDestroy);
}

/// <summary>
/// 泛型方法:创建MonoBehaviour单例
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T CreateMonoSingleton<T>() where T : class, ISingleton
{
T instance = null;
var type = typeof(T);

//判断T实例存在的条件是否满足
if (!IsUnitTestMode && !Application.isPlaying)
return instance;

//判断当前场景中是否存在T实例
instance = UnityEngine.Object.FindObjectOfType(type) as T;
if (instance != null)
{
instance.OnSingletonInit();
return instance;
}

//MemberInfo:获取有关成员属性的信息并提供对成员元数据的访问
MemberInfo info = typeof(T);
//获取T类型 自定义属性,并找到相关路径属性,利用该属性创建T实例
var attributes = info.GetCustomAttributes(true);
foreach (var atribute in attributes)
{
var defineAttri = atribute as MonoSingletonPath;
if (defineAttri == null)
{
continue;
}

instance = CreateComponentOnGameObject<T>(defineAttri.PathInHierarchy, true);
break;
}

//如果还是无法找到instance 则主动去创建同名Obj 并挂载相关脚本 组件
if (instance == null)
{
var obj = new GameObject(typeof(T).Name);
if (!IsUnitTestMode)
UnityEngine.Object.DontDestroyOnLoad(obj);
instance = obj.AddComponent(typeof(T)) as T;
}

instance.OnSingletonInit();
return instance;
}

/// <summary>
/// 在GameObject上创建T组件(脚本)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">路径(应该就是Hierarchy下的树结构路径)</param>
/// <param name="dontDestroy">不要销毁 标签</param>
/// <returns></returns>
private static T CreateComponentOnGameObject<T>(string path, bool dontDestroy) where T : class
{
var obj = FindGameObject(path, true, dontDestroy);
if (obj == null)
{
obj = new GameObject("Singleton of " + typeof(T).Name);
if (dontDestroy && !IsUnitTestMode)
{
UnityEngine.Object.DontDestroyOnLoad(obj);
}
}

return obj.AddComponent(typeof(T)) as T;
}

/// <summary>
/// 查找Obj(对于路径 进行拆分)
/// </summary>
/// <param name="path">路径</param>
/// <param name="build">true</param>
/// <param name="dontDestroy">不要销毁 标签</param>
/// <returns></returns>
private static GameObject FindGameObject(string path, bool build, bool dontDestroy)
{
if (string.IsNullOrEmpty(path))
{
return null;
}

var subPath = path.Split('/');
if (subPath == null || subPath.Length == 0)
{
return null;
}

return FindGameObject(null, subPath, 0, build, dontDestroy);
}
}

/// <summary>
/// 静态类:MonoBehaviour类的单例
/// 泛型类:Where约束表示T类型必须继承MonoSingleton<T>
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class MonoSingleton<T> : MonoBehaviour, ISingleton where T : MonoSingleton<T>
{
/// <summary>
/// 静态实例
/// </summary>
protected static T mInstance;

/// <summary>
/// 静态属性:封装相关实例对象
/// </summary>
public static T Instance
{
get
{
if (mInstance == null && !mOnApplicationQuit)
{
mInstance = SingletonCreator.CreateMonoSingleton<T>();
}

return mInstance;
}
}

/// <summary>
/// 实现接口的单例初始化
/// </summary>
public virtual void OnSingletonInit()
{
}

/// <summary>
/// 资源释放
/// </summary>
public virtual void Dispose()
{
if (SingletonCreator.IsUnitTestMode)
{
var curTrans = transform;
do
{
var parent = curTrans.parent;
DestroyImmediate(curTrans.gameObject);
curTrans = parent;
} while (curTrans != null);

mInstance = null;
}
else
{
Destroy(gameObject);
}
}

/// <summary>
/// 当前应用程序是否结束 标签
/// </summary>
protected static bool mOnApplicationQuit = false;

/// <summary>
/// 应用程序退出:释放当前对象并销毁相关GameObject
/// </summary>
protected virtual void OnApplicationQuit()
{
mOnApplicationQuit = true;
if (mInstance == null) return;
Destroy(mInstance.gameObject);
mInstance = null;
}

/// <summary>
/// 释放当前对象
/// </summary>
protected virtual void OnDestroy()
{
mInstance = null;
}

/// <summary>
/// 判断当前应用程序是否退出
/// </summary>
public static bool IsApplicationQuit
{
get { return mOnApplicationQuit; }
}
}

/// <summary>
/// MonoSingleton路径
/// </summary>
[AttributeUsage(AttributeTargets.Class)] //这个特性只能标记在Class上
public class MonoSingletonPath : Attribute
{
private string mPathInHierarchy;

public MonoSingletonPath(string pathInHierarchy)
{
mPathInHierarchy = pathInHierarchy;
}

public string PathInHierarchy
{
get { return mPathInHierarchy; }
}
}

/// <summary>
/// 继承Mono的属性单例?
/// </summary>
/// <typeparam name="T"></typeparam>
public static class MonoSingletonProperty<T> where T : MonoBehaviour, ISingleton
{
private static T mInstance;

public static T Instance
{
get
{
if (null == mInstance)
{
mInstance = SingletonCreator.CreateMonoSingleton<T>();
}

return mInstance;
}
}

public static void Dispose()
{
if (SingletonCreator.IsUnitTestMode)
{
UnityEngine.Object.DestroyImmediate(mInstance.gameObject);
}
else
{
UnityEngine.Object.Destroy(mInstance.gameObject);
}

mInstance = null;
}
}

/// <summary>
/// 如果跳转到新的场景里已经有了实例,则不创建新的单例(或者创建新的单例后会销毁掉新的单例)
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class PersistentMonoSingleton<T> : MonoBehaviour where T : Component
{
protected static T mInstance;
protected bool mEnabled;

/// <summary>
/// Singleton design pattern
/// </summary>
/// <value>The instance.</value>
public static T Instance
{
get
{
if (mInstance == null)
{
mInstance = FindObjectOfType<T>();
if (mInstance == null)
{
var obj = new GameObject();
mInstance = obj.AddComponent<T>();
}
}

return mInstance;
}
}

/// <summary>
/// On awake, we check if there's already a copy of the object in the scene. If there's one, we destroy it.
/// </summary>
protected virtual void Awake()
{
if (!Application.isPlaying)
{
return;
}

if (mInstance == null)
{
//If I am the first instance, make me the Singleton
mInstance = this as T;
DontDestroyOnLoad(transform.gameObject);
mEnabled = true;
}
else
{
//If a Singleton already exists and you find
//another reference in scene, destroy it!
if (this != mInstance)
{
Destroy(this.gameObject);
}
}
}
}

/// <summary>
/// 如果跳转到新的场景里已经有了实例,则删除已有示例,再创建新的实例
/// </summary>
/// <typeparam name="T"></typeparam>
public class ReplaceableMonoSingleton<T> : MonoBehaviour where T : Component
{
protected static T mInstance;
public float InitializationTime;

/// <summary>
/// Singleton design pattern
/// </summary>
/// <value>The instance.</value>
public static T Instance
{
get
{
if (mInstance == null)
{
mInstance = FindObjectOfType<T>();
if (mInstance == null)
{
GameObject obj = new GameObject();
obj.hideFlags = HideFlags.HideAndDontSave;
mInstance = obj.AddComponent<T>();
}
}

return mInstance;
}
}

/// <summary>
/// On awake, we check if there's already a copy of the object in the scene. If there's one, we destroy it.
/// </summary>
protected virtual void Awake()
{
if (!Application.isPlaying)
{
return;
}

InitializationTime = Time.time;

DontDestroyOnLoad(this.gameObject);
// we check for existing objects of the same type
T[] check = FindObjectsOfType<T>();
foreach (T searched in check)
{
if (searched != this)
{
// if we find another object of the same type (not this), and if it's older than our current object, we destroy it.
if (searched.GetComponent<ReplaceableMonoSingleton<T>>().InitializationTime < InitializationTime)
{
Destroy(searched.gameObject);
}
}
}

if (mInstance == null)
{
mInstance = this as T;
}
}
}
}

简单介绍基本使用

SingletonKit使用指南

标准C#单例的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using UnityEngine;

namespace QFramework.Example
{
internal class Class2Singleton : Singleton<Class2Singleton>
{
private static int mIndex = 0;//记录当前单例的序号,注意这个是静态变量,此Singleton销毁之后静态变量不会变
private Class2Singleton() { }//标准C#单例必须有私有构造,防止在其他地方实例化

public override void OnSingletonInit()
{
mIndex++;
}

public void Log(string content)
{
Debug.Log("Class2Singleton" + mIndex + ":" + content);
}
}

public class Singleton : MonoBehaviour
{
private void Start()
{
Class2Singleton.Instance.Log("Hello World!");

Class2Singleton.Instance.Dispose();//销毁这个单例

Class2Singleton.Instance.Log("I'm Back!");
}
}
}

输出结果

MonoSingleton的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System.Collections;
using UnityEngine;

namespace QFramework.Example
{
internal class Class2MonoSingleton : MonoSingleton<Class2MonoSingleton>
{
public override void OnSingletonInit()
{
Debug.Log(name + ":" + "OnSingletonInit");
}

private void Awake()
{
Debug.Log(name + ":" + "Awake");
}

private void Start()
{
Debug.Log(name + ":" + "Start");
}

protected override void OnDestroy()
{
base.OnDestroy();
Debug.Log(name + ":" + "OnDestroy");
}
}

public class Singleton : MonoBehaviour
{
private IEnumerator Start()
{
var instance = Class2MonoSingleton.Instance;
yield return new WaitForSeconds(3.0f);
instance.Dispose();
}
}
}

Mono单例

注意调用顺序,先Awake,再OnSingletonInit

SingletonProperty

通过接口+属性,从而实现多继承,C#的类是不支持多继承的,使用这种方法来解决这个问题,即实现单例又能继承其他父类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using UnityEngine;

namespace QFramework.Example
{
internal class Class2SingletonProperty : ISingleton
{
public static Class2SingletonProperty Instance
{
get { return SingletonProperty<Class2SingletonProperty>.Instance; }
}

private Class2SingletonProperty() { }
private static int mIndex = 0;//注意这个是静态变量,此Singleton销毁之后静态变量不会变
public void OnSingletonInit()
{
mIndex++;
}
public void Dispose()
{
SingletonProperty<Class2SingletonProperty>.Dispose();//SingletonProperty内部方法都是静态的,所以可以这么写
}
public void Log(string content)
{
Debug.Log("Class2SingletonProperty" + mIndex + ":" + content);
}
}

public class Singleton : MonoBehaviour
{
private void Start()
{
Class2SingletonProperty.Instance.Log("Hello World!");

Class2SingletonProperty.Instance.Dispose();//销毁这个单例

Class2SingletonProperty.Instance.Log("I'm Back!");
}
}
}

输出结果:

1
2
Class2SingletonProperty1:Hello World!
Class2SingletonProperty2:I'm Back!

MonoSingletonProperty

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System.Collections;
using UnityEngine;

namespace QFramework.Example
{
//MyBehaviour封装了MonoBehaviour,这种情况是MonoSingletonProperty的常用情况
//如果我们使用了Class2MonoSingletonProperty : MonoSingleton<Class2MonoSingletonProperty>
//就无法使用自己封装的MyBehaviour了
internal class Class2MonoSingletonProperty : MyBehaviour,ISingleton
{
public static Class2MonoSingletonProperty Instance
{
get { return MonoSingletonProperty<Class2MonoSingletonProperty>.Instance; }
}

public void Dispose()
{
MonoSingletonProperty<Class2MonoSingletonProperty>.Dispose();
}
public override void OnSingletonInit()
{
Debug.Log(name + ":" + "OnSingletonInit");
}

private void Awake()
{
Debug.Log(name + ":" + "Awake");
}

private void Start()
{
Debug.Log(name + ":" + "Start");
}

protected override void OnDestroy()
{
base.OnDestroy();
Debug.Log(name + ":" + "OnDestroy");
}
}

public class Singleton : MonoBehaviour
{
private IEnumerator Start()
{
var instance = Class2MonoSingletonProperty.Instance;
yield return new WaitForSeconds(3.0f);
instance.Dispose();
}
}
}

MonoSingletonPath特性

使用此特性来整理场景中的Mono单例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using UnityEngine;

namespace QFramework.Example
{
[QFramework.MonoSingletonPath("[Example]/MonoSingletonPath")]
internal class ClassUseMonoSingletonPath : MonoSingleton<ClassUseMonoSingletonPath>
{

}

public class Singleton : MonoBehaviour
{
private void Start()
{
var instance = ClassUseMonoSingletonPath.Instance;
}
}
}

Mono单例按照特性中的文件名整理

PersistentMonoSingleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System.Collections;
using UnityEngine;

namespace QFramework.Example
{
internal class GameManager : PersistentMonoSingleton<GameManager>
{

}

public class Singleton : MonoBehaviour
{
private IEnumerator Start()
{
var instance = GameManager.Instance;

new GameObject().AddComponent<GameManager>();//尝试添加新的PersistentMonoSingleton

yield return new WaitForEndOfFrame();//等待一帧

Debug.Log(FindObjectsOfType<GameManager>().Length);//新的PersistentMonoSingleton在Awake时删除了自己,这里Length是1

Debug.Log(instance == FindObjectOfType<GameManager>());//返回true
}
}
}

如果前场景中有一个PersistentMonoSingleton,下一个场景中也挂载有一个同类的PersistentMonoSingleton,则下一个场景中的PersistentMonoSingleton会被删除

常用于音频管理器

RepalceableMonoSingleton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace QFramework.Example
{
internal class GameManager : ReplaceableMonoSingleton<GameManager>
{

}

public class Singleton : MonoBehaviour
{
private IEnumerator Start()
{
var instance = GameManager.Instance;

new GameObject().AddComponent<GameManager>();//尝试添加新的ReplaceableMonoSingleton

yield return new WaitForEndOfFrame();//等待一帧

Debug.Log(FindObjectsOfType<GameManager>().Length);//新的ReplaceableMonoSingleton在Awake时删除了旧的ReplaceableMonoSingleton,这里Length是1

Debug.Log(instance == FindObjectOfType<GameManager>());//返回false
}
}
}

如果前场景中有一个ReplaceableMonoSingleton,下一个场景中也挂载有一个同类的ReplaceableMonoSingleton,则之前场景中的ReplaceableMonoSingleton会被删除

常用于音频管理器