C#泛型單例

1.不支持非公共的無參構造函數的

using System;
using UnityEngine;
public abstract class Singleton<T> where T : class, new()
{
	private static T m_instance;
	public static T instance
	{
		get
        {
            if (Singleton<T>.m_instance == null)
		    {
			    Singleton<T>.m_instance = Activator.CreateInstance<T>();
			    if (Singleton<T>.m_instance != null)
			    {
                    (Singleton<T>.m_instance as Singleton<T>).Init();
			    }
		    }

            return Singleton<T>.m_instance;
        }
	}

	public static void Release()
	{
		if (Singleton<T>.m_instance != null)
		{
			Singleton<T>.m_instance = (T)((object)null);
		}
	}

    public virtual void Init()
    {

    }

    public abstract void Dispose();

}

2.支持非公共的無參構造函數的

public class BaseInstance<T> where T : class//new(),new不支持非公共的無參構造函數 
    {
        /*
         * 單線程測試通過!
         * 多線程測試通過!
         * 根據需要在調用的時候才實例化單例類!
          */
        private static T _instance;
        private static readonly object SyncObject = new object();
        public static T Instance
        {
            get
            {
                if (_instance == null)//沒有第一重 singleton == null 的話,每一次有線程進入 GetInstance()時,均會執行鎖定操作來實現線程同步,
                //非常耗費性能 增加第一重singleton ==null 成立時的情況下執行一次鎖定以實現線程同步
                {
                    lock (SyncObject)
                    {
                        if (_instance == null)//Double-Check Locking 雙重檢查鎖定
                        {
                            //_instance = new T();
                            //需要非公共的無參構造函數,不能使用new T() ,new不支持非公共的無參構造函數 
                            _instance = (T)Activator.CreateInstance(typeof(T), true); //第二個參數防止異常:“沒有爲該對象定義無參數的構造函數。”
                        }
                    }
                }
                return _instance;
            }
        }
        public static void SetInstance(T value)
        {
            _instance = value;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章