Singleton

代碼以下:html

    public class Singleton<T> where T : class
    {
        private static T _instance;
        private static readonly object _lock = new object();

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = (T)Activator.CreateInstance(typeof(T), true);
                        }
                    }
                }
                return _instance;
            }
        }
    }

使用:spa

    public class User : Singleton<User>
    {
        private User() { }
    }

 

Implementing the Singleton Pattern in C# 中文版

相關文章
相關標籤/搜索