singleton pattern C# 继承式 模板

来源:互联网 发布:软件 地图 编辑:程序博客网 时间:2024/06/01 08:31

//继承式

    public abstract class Singleton<T> where T : new()    {        private static T m_instance;        static object m_lock = new object();        public static T Instance        {            get            {                if (m_instance == null)                {                    lock (m_lock)                    {
if(m_instance == null)                        m_instance = new T();                    }                }                return m_instance;            }        }    }    class SingletonInstance : Singleton<SingletonInstance>    {        public void Print()        {            Console.WriteLine("SingletonInstance");        }    }


   public static class Singleton<T> where T : new()    {        static T _instance;        static object _lock = new object();        static Singleton()        {        }        public static T Instance        {            get            {                if (_instance == null)                    lock (_lock)                    {                        if (_instance == null)                        {                            _instance = new T();                        }                    }                return _instance;            }        }    }


原创粉丝点击