單列 單件安全

// ===============================================================================
// 簡述 : 單件安全
// ===============================================================================
using UnityEngine;
using System.Collections;
using System.Reflection;
using System;
using System.Collections.Generic;

//非繼承MonoBehaviour的單例繼承此類,並加入私有構造函數
public class TSingleton<T> where T: class//, new()
{
    private static T _instance;  
    private static readonly object syslock=new object();
    public static readonly Type[] EmptyTypes = new Type[0];
    public static T Instance 
    {  
        get
        {
            if (_instance == null)
            {
                lock (syslock)
                {
                    if (_instance == null)
                    {
                        ConstructorInfo ci = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, EmptyTypes, null);
                        if (ci == null) { throw new InvalidOperationException("class must contain a private constructor"); }
                        _instance = (T)ci.Invoke(null);
                        //_instance = new T();  
                    }
                }
            }
            return _instance;  
        }
    }
    public virtual void Update() { }
    public virtual void FixedUpdate() { }
    public virtual void LateUpdate() { }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章