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

单例模式

时间:2017-12-11 18:43:29      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:type   nload   跳转   div   blog   模式   ted   unit   单例模式   

using UnityEngine;
using System.Collections;

namespace SingleTonBases
{

#region 不继承Mono

/// <summary>
/// 不继承Mono的单例
/// SingleTonBase<T> where T : new ()
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingleTonBase<T> where T : new()
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = new T();
}
return _instance;
}
}
}

/// <summary>
/// 不继承自Mono的事例
/// Singleton<T> : System.IDisposable where T : new()
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Singleton<T> : System.IDisposable where T : new()
{
private static T instance;

public static T Instance
{
get
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}

public virtual void Dispose()
{

}
}

#endregion


#region 继承Mono

/// <summary>
/// 继承自Mono的单例
/// 可挂可不挂在游戏物体上
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class MonoSingleTon<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;

public static T Instance
{
get
{
if (_instance == null)
{
GameObject obj = new GameObject(typeof(T).Name);
_instance = obj.AddComponent<T>();
}
return _instance;
}
}

/// <summary>
/// 可重写的虚方法,用于实例化对象
/// </summary>
protected virtual void Awake()
{
_instance = this as T;
}
}

/// <summary>
/// 继承自Mono的单例
/// 可挂可不挂在游戏物体上
/// 跳转场景不销毁对象(DontDestroyOnLoad)
/// </summary>
/// <typeparam name="T"></typeparam>
public class MonoSingleTonDontDestroyOnLoad<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;

public static T Instance
{
get
{
if (_instance == null)
{
GameObject obj = new GameObject(typeof(T).Name);
_instance = obj.AddComponent<T>();
}
return _instance;
}
}

/// <summary>
/// 可重写的虚方法,用于实例化对象
/// </summary>
protected virtual void Awake()
{
_instance = this as T;
DontDestroyOnLoad(this);
}
}

#endregion

}

单例模式

标签:type   nload   跳转   div   blog   模式   ted   unit   单例模式   

原文地址:http://www.cnblogs.com/0315cz/p/8024045.html

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