夜微凉、的博客

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

单例模式即所谓的一个类只能有一个实例, 也就是类只能在内部实例一次,然后提供这一实例,外部无法对此类实例化。

单例模式的特点:

1、只能有一个实例;

2、只能自己创建自己的唯一实例;

3、必须给所有其他的对象提供这一实例。

普通单例模式(没有考虑线程安全)

  /// <summary>
    /// 单例模式
    /// </summary>
    public class Singleton
    { 
        private static Singleton singleton;

        private Singleton() { }

        /// <summary>
        /// 获取实例-线程非安全模式
        /// </summary>
        /// <returns></returns>
        public static Singleton GetSingleton()
        {
            if (singleton == null)
                singleton = new Singleton();
            return singleton;
        } 
    }

考虑多线程安全

/// <summary>
    /// 单例模式
    /// </summary>
    public class Singleton
    {
        private static object obj = new object();

        private static Singleton singleton;

        private Singleton() { }

        /// <summary>
        /// 获取实例-线程安全
        /// </summary>
        /// <returns></returns>
        public static Singleton GetThreadSafeSingleton()
        {
            if (singleton == null)
            {
                lock (obj)
                {
                    if (singleton == null)
                    {
                        singleton = new Singleton();
                    }
                }
            }
            return singleton;
        }
    }

 

posted on 2018-02-26 20:41  夜、微凉  阅读(4412)  评论(2编辑  收藏  举报