1. 程式人生 > >單例模式通用類

單例模式通用類

csharp esp brush sys instance type spa space create

namespace System
{
    /// <summary>
    /// 為指定的實例創建有線程安全的單例模式。實例必須有一個公開的,無參數的構造方法,並且能正確的被實例化。
    /// </summary>
    /// <typeparam name="T">作為單例的對象。</typeparam>
    public static class Singleton<T>
       where T : class
    {
        static volatile T _instance;
        static object _lock = new object();

        /// <summary>

        /// 為指定對象創建實例。

        /// </summary>

        public static T CreateInstance()
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = Activator.CreateInstance<T>();
                    }
                }
            }
            return _instance;
        }
    }
}

  

單例模式通用類