单例管理类代码
/**********************************************************************
*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<SingletonContainer>
{
public T GetInstance<T>() where T : new()
{
string singletonName = typeof(T).ToString();
T singleton = Container<T>.Get(singletonName);
if (singleton == null)
{
singleton = new T();
Container<T>.Set(singletonName, singleton);
}
return singleton;
}
private static class Container<T>
{
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:zhiheng.rick@gmail.com
*All rights reserved.
*FileName: BaseFlow.cs
*Author: zhiheng.shao email:zhiheng.rick@gmail.com
*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<T> : IState<GameFlowController> where T : BaseFlow<T>, new()
{
public static T Instance
{
get
{
return SingletonContainer.Instance.GetInstance<T>();
}
}
/// <summary> 获取状态名 </summary>
/// <returns></returns>
public string GetStateName()
{
return GetType().ToString();
}
public abstract void Enter();
public abstract void Exit();
}
}