普通的C#单例模式(简单)
public class Singleton<T> where T :new() {
private static T m_Instance;
public static T Instance {
get {
if (m_Instance == null) {
m_Instance = new T();
}
return m_Instance;
}
}
}
普通的C#单例模式(多线程安全机制)
public abstract class Singleton<T> where T : class, new()
{
private static T instance = null;
// 多线程安全机制
private static readonly object locker = new object();
public static T Instance
{
get
{
lock (locker)
{
if (instance == null)
instance = new T();
return instance;
}
}
}
}
单例模式(继承需要一个非公有的无参构造函数)
/// <summary>
/// 单例
/// 继承需要一个非公有的无参构造函数
/// </summary>
/// <typeparam name="T">类名的泛型</typeparam>
public abstract class Singleton2<T> where T : class
{
private static T instance = null;
// 多线程安全机制
private static readonly object locker = new object();
public static T Instance
{
get
{
// 线程锁
lock (locker)
{
if (null == instance)
{
// 反射获取实例
var octors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
// 获取无参数的非公共构造函数
var octor = Array.Find(octors, c => c.GetParameters().Length == 0);
// 没有则提示没有私有的构造函数
if (null == octor)
{
throw new Exception("No NonPublic constructor without 0 parameter");
}
// 实例化
instance = octor.Invoke(null) as T;
}
return instance;
}
}
}
/// <summary>
/// 构造函数
/// 避免外界new
/// </summary>
protected Singleton2() { }
}
继承MonoBehaviour的单例模式(一)
using UnityEngine;
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
//if (FindObjectOfType<T>() > 1)
//{
// return FindObjectOfType<T>;
//}
if (_instance == null)
{
_instance = new GameObject(typeof(T).ToString()).AddComponent<T>();
}
}
return _instance;
}
}
}
继承MonoBehaviour的单例模式(二)
using UnityEngine;
public class MonoSingleton<T> : MonoBehaviour where T :MonoSingleton<T> {
protected static T instance;
public static T Instance
{
get { return instance; }
}
protected virtual void Awake()
{
if (instance == null)
{
instance = (T)this;
}
else
{
Debug.LogError("Get a second instance of this class" + this.GetType());
}
}
}
继承MonoBehaviour的单例模式(三),带初始化函数
/// <summary>
/// 单例[继承MonoBehaviour带Awake]
/// </summary>
public class MonoSingleton2<T> : MonoBehaviour where T : MonoSingleton2<T>
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
Debug.LogError(typeof(T).ToString() + " is NULL.");
return _instance;
}
}
private void Awake()
{
if (_instance != null)
{
//one more Initialize
Debug.LogError(typeof(T).ToString() + " aready have one on" + _instance.gameObject.name);
}
_instance = this as T;//or _instance = (T)this;
//call Init
Init();
}
/// <summary>
/// 需要在awake初始化的请重载Init
/// </summary>
protected virtual void Init()
{
//optional to override
}
}
参考博客地址如下
1、https://www.cnblogs.com/koshio0219/p/11203631.html
2、https://www.codetd.com/article/11599698
3、https://blog.csdn.net/u014361280/article/details/103868778