码迷,mamicode.com
首页 > 其他好文 > 详细

通用单例类

时间:2019-08-18 18:11:21      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:for   str   component   monit   load   monitor   类设计   vat   return   

普通单例类设计:

public abstract class Singleton<T> where T : new()
{
    private static T _instance;
    private static object _lock = new object();

    public static T instance
    {
        get
        {
            if (_instance == null)
            {
                object lockObject = Singleton<T>._lock;
                Monitor.Enter(lockObject);
                try
                {
                    if (_instance == null)
                        _instance = Activator.CreateInstance<T>();
                }
                finally
                {
                    Monitor.Exit(lockObject);
                }
            }
            return _instance;
        }
    }

    //public virtual void Init()
    //{

    //}
}

 

MomoBehavior类的设计:

 

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T instance = null;
    private static object lockObject = new object();

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                object obj = MonoSingleton<T>.lockObject;
                Monitor.Enter(obj);
                instance = GameObject.FindObjectOfType(typeof(T)) as T;
                if (instance == null)
                {
                    instance = new GameObject(typeof(T).Name, typeof(T)).GetComponent<T>();
                }
                Monitor.Exit(obj);
            }
            return instance;
        }
    }

    public virtual void SetDontDestroyOnLoad(Transform parent)
    {
        transform.parent = parent;
    }
}

 

通用单例类

标签:for   str   component   monit   load   monitor   类设计   vat   return   

原文地址:https://www.cnblogs.com/Z-59-46/p/11372751.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!