单例模式

单例模式特点:

  • 单例类只能有一个实例。
  • 单例类必须自己创建自己的唯一实例。
  • 单例类必须给所有其他对象提供这一实例。
  • 构造函数是私有的。
  • 没有接口,不能继承(C#最好用sealed class,此修饰符会阻止其他类从该类继承)。

使用场景:

  • 要求生产唯一序列号。
  • WEB 中的计数器,不用每次刷新都在数据库里加一次,用单例先缓存起来。
  • 创建的一个对象需要消耗的资源过多,比如 I/O 与数据库的连接等。

实现一:

  • 懒汉式
  • 线程安全
  • Lazy(延迟加载)
  • 避免内存浪费
    public sealed class Singleton
    {
        private static Singleton instance;
        private static readonly object syncRoot = new object();
        private Singleton() { }

        public static Singleton GetInstance()
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }

实现二:

  • 饿汉式 
  • 线程安全
  • UnLazy  (非延迟加载)
  • 执行效率高
    public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton();
        private Singleton() { }
        public static Singleton GetInstance()
        {
            return instance;
        }
    }

使用:

   static void Main(string[] args)
        {
            Singleton s1 = Singleton.GetInstance();
            Singleton s2 = Singleton.GetInstance();

            if (s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }

            Console.Read();
        }

打印结果:

 

posted @ 2018-01-18 09:56  .追风逐月  阅读(133)  评论(0编辑  收藏  举报