Skip to content

Commit 5aae3a3

Browse files
committed
加入SingletonPatternExample3-抽象泛型单例基类
加入SingletonPatternExample3-抽象泛型单例基类
1 parent a680f66 commit 5aae3a3

File tree

5 files changed

+105
-0
lines changed

5 files changed

+105
-0
lines changed

Assets/Creational Patterns/Singleton Pattern/Example3.meta

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
//-------------------------------------------------------------------------------------
2+
// SingletonPatternExample3.cs
3+
//-------------------------------------------------------------------------------------
4+
5+
using UnityEngine;
6+
using System.Collections;
7+
8+
namespace SingletonPatternExample3
9+
{
10+
11+
public class SingletonPatternExample3 : MonoBehaviour
12+
{
13+
void Start()
14+
{
15+
//单例A
16+
SingletonA.Instance.DoSomething();
17+
18+
//单例B
19+
SingletonB.Instance.DoSomething();
20+
}
21+
22+
}
23+
24+
/// <summary>
25+
/// 单例类基类(抽象类、泛型,其他类只需继承此类即可成为单例类)
26+
/// 继承该类的,即成为一个单例类
27+
/// </summary>
28+
public abstract class Singleton<T>
29+
where T : class, new()
30+
{
31+
private static T _instance = null;
32+
33+
public static T Instance
34+
{
35+
get
36+
{
37+
if (_instance == null)
38+
{
39+
_instance = new T();
40+
return _instance;
41+
}
42+
return _instance;
43+
}
44+
}
45+
46+
protected virtual void Awake()
47+
{
48+
_instance = this as T;
49+
}
50+
}
51+
52+
53+
/// <summary>
54+
/// 继承自Singleton<T>的单例
55+
/// </summary>
56+
public class SingletonA : Singleton<SingletonA>
57+
{
58+
public void DoSomething()
59+
{
60+
Debug.Log("SingletonA:DoSomething!");
61+
}
62+
}
63+
64+
/// <summary>
65+
/// 继承自Singleton<T>的单例
66+
/// </summary>
67+
public class SingletonB : Singleton<SingletonB>
68+
{
69+
public void DoSomething()
70+
{
71+
Debug.Log("SingletonB:DoSomething!");
72+
}
73+
}
74+
75+
76+
}

Assets/Creational Patterns/Singleton Pattern/Example3/SingletonPatternExample3.cs.meta

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Binary file not shown.

Assets/Creational Patterns/Singleton Pattern/Example3/SingletonPatternExample3.unity.meta

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)