zoukankan      html  css  js  c++  java
  • 设计模式-单例模式(创建型)

    1 单例模式

    1.0 需求

    类的对象只能存在一个。

    1.1 实现

    使用类的静态对象成员保存唯一的单例对象,然后将构造函数设为private。

    通过一个静态函数返回保存的单例对象。

    依据静态数据成员创建的时机分为:程序加载时创建(直接new),首次需要的时候创建(get中先判断是否为null)

    在多线程中,延时创建会导致争用,因此采用两段判断的形式。

    class Singleton
    {
      private:
        Singleton() = default;
        static Singleton *_instance;
    
      public:
        static Singleton *instance();
        static bool freeInstance();
        Mutex lock;
    };
    
    //惰性模式,不访问不创建,在第一次访问的时候创建
    //对静态变量的初始化必需放在类的外部
    Singleton Singleton::*_instance = nullptr;
    Singleton Singleton::*instance()
    {
        // 两段判断的形式
        if (_instance = nullptr)
        {
            MutexLock lock(lock);
            if (_instance = nullptr)
            {
                _instance = new Singleton();
            }
        }
        return _instance;
    }
    
    //非惰性模式
    //在程序一运行就进行了初始化
    Singleton Singleton::*_instance = new Singleton();
    Singleton Singleton::*instance()
    {
        return _instance;
    }
    
    bool Singleton::freeInstance()
    {
        if (_instance != nullptr)
        {
            delete _instance;
            _instance = nullptr;
        }
    }
    

      

    单例模式的派生类也是单例模式

    原文

    // 每个派生体系都公用一个基类实例。
    template <class T>
    class Singleton
    {
      private:
        static T *m_Instance;
    
      protected:
        Singleton(){};
        Singleton(const Singleton &);
    
      public:
        static T *Get_Instance() 
        {
            if(m_Instance == nullptr)
            {
                m_Instance =new T; //这里生成的是T
            }
            return m_Instance;
        }
        static void Free_Instance();
    };
    
    // public 继承的原因在于,派生类需要使用 Get_Instance 和 Free_Instance;
    class test : public Singleton<test>
    { 
        // 声明为 友元原因在于需要调用 Singleton 中的 Get_Instance 需要 new T ,需要
        // 调用本类 的构造函数。
        friend class Singleton<test>;
      private:
        test() {}
    
      public:
        //do
    };
    

      

     

  • 相关阅读:
    5G名词术语
    什么是IPv6
    如何用SecureCRT 登录eNSP模拟器里的设备
    numpy-排序
    numpy-tile 数组复制
    经纬度计算距离与方位角
    numpy-添加操作大全
    高效编程之 concurrent.future
    linux命令 集合
    PostgreSQL-表空间
  • 原文地址:https://www.cnblogs.com/perfy576/p/8551431.html
Copyright © 2011-2022 走看看