【亮亮笔记】普通类的泛型单例模式,与Unity脚本的泛型单例模式

普通类的泛型单例模式:
using System;

/// 
///     TODO:普通泛型类的单例模式
/// 
public abstract class SingletonPattern
        where T : new()//TODO:对泛型 T 进行约束,T  必须具有公共无参数构造函数。 与其他约束一起使用时,new() 约束必须最后指定。
    {
        private static T _Instance;

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

Unity脚本的泛型单例模式

using UnityEngine;

/// 
/// TODO: 泛型的单例模式模板、共用类
/// 
/// 想要变成单例的类
public abstract class UnityScriptSingletonPattern : MonoBehaviour
    where T : MonoBehaviour //TODO:对泛型 T 进行约束, T 必须是继承自monobeheaviour
{
    private static T _Instance = null;

    public static T Instance
    {
        get { return _Instance; }
    }

    /// 
    /// TODO:因为Unity脚本的单例模式与普通类的单例模式写法不一样,所以这里限制非Mono的类不能继承。否则会报错
    /// 
    protected virtual void Awake()
    {
        _Instance = this as T;
    }
}
提供对泛型进行约束的说明 类型参数的约束(C# 编程指南)

你可能感兴趣的:(Unity,单例模式,C#)