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

  

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

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

  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值