【Unity】非MonoBehaviour子类的单例管理

单例管理类代码

/**********************************************************************
 *Copyright(C) 2016 by zhiheng.shao
 *All rights reserved.
 *FileName:     SingletonContainer.cs
 *Author:       zhiheng.shao
 *Version:      1.0
 *UnityVersion:5.3.3f1
 *Date:         2016-04-20
 *Description:   
 *History:  
**********************************************************************/
using UnityEngine;
using System.Collections.Generic;
using System.Collections;

namespace Rickshao.Singleton
{
    public class SingletonContainer : Singleton
    { 
        public T GetInstance() where T : new()
        {
            string singletonName = typeof(T).ToString();
            T singleton = Container.Get(singletonName);
            if (singleton == null)
            {
                singleton = new T();
                Container.Set(singletonName, singleton);
            }
            return singleton;
        }

        private static class Container
        {
            private static Dictionary<string, T> m_Collections = new Dictionary<string, T>();

            public static Dictionary<string, T> Collections { get { return m_Collections; } }

            public static T Get(string singletonName)
            {
                if (m_Collections.ContainsKey(singletonName))
                {
                    return (T)m_Collections[singletonName];
                }
                return default(T);
            }

            public static void Set(string singletonName, T singleton)
            {
                m_Collections.Add(singletonName, singleton);
            }
        }
    }
}

使用示例

/*********************************************************************************
 *Copyright(C) 2016 by zhiheng.shao email:[email protected]
 *All rights reserved.
 *FileName:     BaseFlow.cs
 *Author:       zhiheng.shao email:[email protected]
 *Version:      1.0
 *UnityVersion:5.3.5f1
 *Date:         2016-07-21
 *Description:   
 *History: 
**********************************************************************************/
using UnityEngine;
using System.Collections;
using Rickshao.StateMachine;
using Rickshao.Singleton;

//TODO: 换成单例
namespace KickBall.Main.GameFlow
{
    public abstract class BaseFlow : IState where T : BaseFlow, new()
    {
        public static T Instance 
        {
            get 
            {
                return SingletonContainer.Instance.GetInstance();
            }
        }

        ///  获取状态名 
        /// 
        public string GetStateName() 
        {
            return GetType().ToString();
        }

        public abstract void Enter();

        public abstract void Exit();
    }
}

你可能感兴趣的:(C#,UGUI,unity)