/// <summary>
    /// 单线程单件模式示例代码
    /// 此单件模式在多线程程序,不能达到预期的目的]
    /// 其中volatile表示编译器不再对代码优化排序
    /// </summary>
    class Singleton
    {
        private static volatile Singleton instance = null;
        /// <summary>
        ///私有了构造方法
        /// </summary>
        private Singleton() { }

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }

    /// <summary>
    /// 多线程单件模式代码
    /// </summary>

    class SingletonTest
    {
        private static volatile Singleton instance = null;
        /// <summary>
        /// 提供一个临时对象,保证只有一个对象访问此下面的代码,但容易造成死锁现象
        /// </summary>
        public object temp = new object();
        /// <summary>
        ///私有了构造方法
        /// </summary>
        private SingletonTest() { }

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {

                    lock (temp)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton();
                        }
                    }
                }
                return instance;
            }
        }
    }

    /// <summary>
    /// 单件模式的另一种实现
    /// </summary>
    class SingletonSecond
    {
        public static readonly SingletonSecond instance = new SingletonSecond();

        /// <summary>
        /// 静态构造器
        /// 不允许有任何的参数传入,但上面的两个类在构造的时候都可以有参数
        /// 只能有一个静态构造器,此静态构造器由程序自动调用
        /// </summary>
        static SingletonSecond() { }
    }

    /// <summary>
    /// 此类是上述类的详细解释
    /// 下面的代码和上述类的代码一个逻辑,只是详细的解释
    /// </summary>
    class SimpleSingleton
    {
        public static readonly SimpleSingleton instance = new SimpleSingleton();

        static SimpleSingleton()
        {
            new SimpleSingleton();
        }

        private SimpleSingleton() { }
    }

posted on 2009-02-20 23:37  hao a  阅读(284)  评论(0编辑  收藏  举报