singleton pattern C# 继承式 模板

//继承式

    public abstract class Singleton 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
    {
        public void Print()
        {
            Console.WriteLine("SingletonInstance");
        }
    }


   public static class Singleton 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;
            }
        }
    }


你可能感兴趣的:(软件工程)