简单设计模式

单例模式

单线程

保证类仅有一个实例,并提供一个访问它的全局访问点。

  • 构造函数私有化,避免外界使用new来创造实例
  • 通过判断一个局部static变量来确定是否创造实例
  • 通过接口GetInstance来取得实例
    class Singleton {
    private:
      static Singleton instance;
    private:
      Singleton(){...}
    public:
      static Singleton GetInstance()
      {
          if(instance==null) {
              instance = new Singleton();
          }
          return instance;
      }
    };    

    多线程

    多个线程同时访问Singleton类是可能创造多个实例的。
  • 通过对临界区加锁来避免多个线程同时访问GetInstance
  • 避免加锁开销过大,进行优化,只有实例未被创建时再加锁
    class Singleton {
    private:
      static Singleton instance;
      static readonly obj sync = new obj();
    private:    
      Singleton(){...}
    public:
      static Singleton GetInstance()
      {
          if(instance==null) 
          {
              lock(sync)
              {
                  if(instance==null)
                      instance = new Singleton();
              }
          }
          return instance;
      }
    };    

    饿汉模式和懒汉模式

饿汉模式:用静态初始化的方式,类一加载就实例化的对象,提前占用系统资源,但不需要加锁;
懒汉模式:第一次被引用时才会将自己实例化,但是存在线程安全问题,需要加锁。

饿汉模式通过阻止派生,初始化就创建实例来实现。

简单工厂模式

用一个单独的类来做创造实例的过程。如一个计算器的实现。
在这里插入图片描述

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-21 11:29
已编辑
斯卡蒂味的鱼汤:知道你不会来数马,就不捞你😂最近数马疯狂扩招,招聘要求挺低的,你能力肯定够,应该就是因为太强了,知道你不会来才不捞你
投递腾讯云智研发等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务