首页 > Windows开发 > 详细

C#设计模式(1)——单例模式(Singleton)

时间:2018-02-26 21:23:39      阅读:207      评论:0      收藏:0      [点我收藏+]

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

单例模式的特点:

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)
                {
                    singleton = new Singleton();
                }
            }
            return singleton;
        }
    }

 

C#设计模式(1)——单例模式(Singleton)

原文:https://www.cnblogs.com/wwj1992/p/8475953.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!