设计模式——单例

饿汉式

    /// <summary>
    /// 饿汉式
    /// </summary>
    public sealed class SingleTest
    {
        private static SingleTest st = new SingleTest();

        private SingleTest()
        {
        }

        public static SingleTest getInstance()
        {
            return st;
        }

    }

 

 

 

懒汉式(存在线程安全)

    //懒汉式
    public sealed class SingleLazy
    {
        private static SingleLazy sl = null;
        private SingleLazy()
        { }
        public static SingleLazy GetInstance()
        {
            if (sl == null)
            {
                sl = new SingleLazy();
            }
            return sl;
        }
    }

加锁

//懒汉式
    public sealed class SingleLazy
    {
        private static SingleLazy sl = null;
        private static readonly object loker = new object();
        private SingleLazy()
        { }
        public static SingleLazy GetInstance()
        {
            lock (loker)
            {
                if (sl == null)
                {
                    sl = new SingleLazy();
                }
            }
            return sl;
        }
    }

完善加锁:双重锁

/// <summary>
    /// 双重锁定
    /// </summary>
    public sealed class SingleLazy
    {
        private static SingleLazy sl = null;
        private static readonly object loker = new object();
        private SingleLazy()
        { }
        public static SingleLazy GetInstance()
        {

            if (sl == null)
            {
                lock (loker)
                {
                    if (sl == null)
                    {
                        sl = new SingleLazy();
                    }
                }
            }
            return sl;
        }
    }

 

posted on 2017-06-20 14:24  奔游浪子  阅读(56)  评论(0)    收藏  举报

导航