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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM