美文网首页
【设计模式】「单例模式」

【设计模式】「单例模式」

作者: FCLoveShare | 来源:发表于2019-06-21 15:25 被阅读0次

    在游戏开发中,最常用的设计模式化应该是「单例模式」

    比如说,我们在做UI框架的时候,为了防止页面重建,一把都会把界面设计成单例。
    考虑到游戏中有大量的页面需要做,有什么方法,可以省掉我们每次页面都需要编写单例代码吗?
    这就体现出面对对象的优势了
    我们可以创建一个基类来实现单例模式,界面开发只需要继承就好了


    MonoBehavior单例

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

    普通类的单例

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

    单例基类

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

    感谢:@草帽领

    相关文章

      网友评论

          本文标题:【设计模式】「单例模式」

          本文链接:https://www.haomeiwen.com/subject/gegyqctx.html