面向對象想必大家都不陌生,今天我們要說的就是GOF23中設計模式裏面的一個,叫做單例模式。在他的字典裏,不允許有第二個自己存在,要保證實例唯一。他的一般解釋就是,保證一個類只有一個實例,並提供一訪問他的全局訪問點。單例模式因爲封裝他的唯一實例,他就可以嚴格的控制客戶怎樣訪問他以及何時訪問他。
下面我們就設計模式在unity引擎開發中的使用來做一些簡單說明。
簡單來說單例在Unity3d中的使用,方式可以如下:
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
|
using
UnityEngine; using
System.Collections; public
class
SigletonOnlyOne : MonoBehaviour { public
static
SigletonOnlyOne instance; public
void
Start() { if
(instance== null ) { instance
= this ; } } public
string
ShowMsg( string
msg) { return
msg; } } |
優點:不需要重構什麼,直接編碼。方便其他類使用。
缺點:每個要實現單例的類都需要手動寫上相同的代碼,代碼重複對我們來說可不是好事情。同時需要把實現單例的類手動綁定到遊戲對象上纔可以使用。
實現方式二:
1)定義單例模板基類
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
UnityEngine; using
System.Collections; ///
<summary> ///
定義單例模板基類。 ///
</summary> ///
<typeparam name="T"></typeparam> public
class
Singleton<T> : MonoBehaviour where T : MonoBehaviour { private
static
T instance; public
static
T Instance { get
{ return
Singleton<T>.instance; } } public
void
Awake() { if
(instance == null ) { instance
= GetComponent<T>(); } } public
void
OnApplicationQuit() { instance
= null ; Debug.Log( "quit" ); } } |
優點:通過代碼重構,去除掉了重複的代碼。想具有單例功能的類。只需要繼承模板基類就可以具有單例的作用。
缺點:模板單例不需要綁定到遊戲對象,但是被其他腳本調用的需要手動綁定到遊戲對象上纔可以使用。
實現方式三:
1)定義單例模板 基類
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
|
using
UnityEngine; using
System.Collections; ///
<summary> ///
定義單例模板基類。 ///
</summary> ///
<typeparam name="T"></typeparam> public
class
Singleton<T> : MonoBehaviour where T : MonoBehaviour { private
static
T instance; public
static
T Instance { get { if
(instance == null ) { GameObject
singleton = new
GameObject(); singleton.name
= "Singleton" ; instance
= singleton.AddComponent<T>(); } return
instance; } } public
void
OnApplicationQuit() { instance
= null ; Debug.Log( "quit" ); } } |
2)繼承模板基類,實現方式同方式二里的第二步一樣。
優點:不需要手動綁定單例到遊戲對象就可以使用。
缺點:這些都是遊戲對象,在unity3d中只能在主線程中進行調用。所以網絡多線程方面會產生單例的不唯一性,在這裏就可以忽略了。
關於單例模式在unity3d中的使用就到此結束,後續我們介紹更多的設計模式,敬請關注!