C#设计模式
分别是普通的单例类以及继承自MonoBehaviour的单例
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
public abstract class SingletonN<T> where T : class, new()
{
private static T ins = null;
private static readonly object locker = new object();
public static T Ins
{
get
{
if (ins == null)
{
lock (locker)
{
if (ins == null)
{
ins = new T();
}
}
}
return ins;
}
}
}
public class SingletonM<T> : MonoBehaviour where T : SingletonM<T>
{
private static T ins;
public static T Ins
{
get
{
if (ins != null) return ins;
ins = FindObjectOfType<T>();
if (ins == null)
{
new GameObject("Singleton of " + typeof(T)).AddComponent<T>();
}
else ins.Ini();
return ins;
}
}
private void Awake()
{
ins = this as T;
Ini();
}
protected virtual void Ini() { }
}
1
观察者模式, 待补充
本文由作者按照 CC BY 4.0 进行授权