Unity3d设计模式之单例模式

来源:互联网 发布:网络舆论论文 编辑:程序博客网 时间:2024/05/16 16:02

单例模式我相信是所有设计模式之中运用最广泛的设计模式之一。

 

今天我们就来看看在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 () {
 
    }
}

  

其他脚本要调用的时候,直接:

public test2 name;

name = test2.instance;

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()
        {
        }

  

原创粉丝点击