天天看點

unity3d:單例模式,Mono場景唯一,不銷毀;C# where T:new(),泛型限制;Lua單例模式,table ,self

Mono單例

  1. 場景裡挂載了,先找場景裡有的
  2. DontDestroyOnLoad
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Singleton
{
    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        protected static T m_instance = null;


        public static T instance
        {
            get
            {
                if (m_instance == null) 
                {
                    string name = typeof(T).ToString();
                    GameObject gameEntryInstance = GameObject.Find(name); //單例的名字都唯一,防止場景裡已經有了
                    if (gameEntryInstance == null)
                    {
                        gameEntryInstance = new GameObject(name);
                        DontDestroyOnLoad(gameEntryInstance);
                    }
                    if (gameEntryInstance != null)
                    {
                        m_instance = gameEntryInstance.GetComponent<T>();
                    }
                    if (m_instance == null)
                    {
                        m_instance = gameEntryInstance.AddComponent<T>();
                    }
                }

                return m_instance;
            }
        }

        public void StartUp()
        {

        }
        protected void OnApplicationQuit()
        {
            m_instance = null;
        }
    }

}      

c#單例

在對泛型的限制中,最常使用的關鍵字有where 和 new。

其中where關鍵字是限制所使用的泛型,該泛型必須是where後面的類,或者繼承自該類。

new()說明所使用的泛型,必須具有無參構造函數,這是為了能夠正确的初始化對象

/// <summary>
 /// C#單例模式
 /// </summary>
 public abstract class Singleton<T> where T : class,new()
 {
     private static T instance;
     private static object syncRoot = new Object();
     public static T Instance
     {
         get
         {
             if (instance == null)
             {
                 lock (syncRoot)
                 {
                     if (instance == null)
                         instance = new T();
                 }
             }
             return instance;
         }
     }

     protected Singleton()
     {
         Init();
     }

     public virtual void Init() { }
 }      

Lua單例

local function __init(self)
   assert(rawget(self._class_type, "Instance") == nil, self._class_type.__cname.." to create singleton twice!")
   rawset(self._class_type, "Instance", self)
end

local function __delete(self)
   rawset(self._class_type, "Instance", nil)
end

local function GetInstance(self)
   if rawget(self, "Instance") == nil then
      rawset(self, "Instance", self.New())
   end
   assert(self.Instance ~= nil)
   return self.Instance
end      
local ResourcesManager = BaseClass("ResourcesManager", Singleton)      

繼續閱讀