Unity3d设计模式之单例模式
单例模式我相信是所有设计模式之中运用最广泛的设计模式之一。
今天我们就来看看在unity中如何使用单例模式,在unity中,我们分两种单例,一种是继承monobehavior的单例,一种是普通单例。
1.MonoBehavior单例
其实在unity中,如果脚本是继承monobehavior,那么使用起单例来更加简单。
只需要在Awake()里面,添加一句instance = this;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
using UnityEngine; using System.Collections; public class test2 : MonoBehaviour { public static test2 instance; // Use this for initialization void Awake () { instance = this ; } // Update is called once per frame void Update () { } } |
2.普通类的单例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
using UnityEngine; using System.Collections; public class test2 { private static test2 instance; public static test2 Instance { get { if ( null == instance) instance = new test2(); return instance; } set { } } } |
那么问题也就来了,细心的读者会发现,如果项目中有很多个单例,那么我们就必须每次都写这些代码,有什么办法可以省去这些不必要的代码呢?有,那就是面向对象最重要的思想:继承。
今天我们就来学习下,自己封装一个单例类,只要项目中用到单例的话,就从这个单例类继承,把它变成单例。
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
|
public class Singleton<T> where T : new () { private static T s_singleton = default (T); private static object s_objectLock = new object (); public static T singleton { get { if (Singleton<T>.s_singleton == null ) { object obj; Monitor.Enter(obj = Singleton<T>.s_objectLock); //加锁防止多线程创建单例 try { if (Singleton<T>.s_singleton == null ) { Singleton<T>.s_singleton = (( default (T) == null ) ? Activator.CreateInstance<T>() : default (T)); //创建单例的实例 } } finally { Monitor.Exit(obj); } } return Singleton<T>.s_singleton; } } protected Singleton() { } |
:http://www.cnblogs.com/CaomaoUnity3d/p/4732787.html