




























单例模式,指的是,在一些特定的场景当中,某一些类只能创建出一个实例(对象)。无论是单线程还是多线程环境下面,都只能生成一个对象,这个时候,就需要使用到单例模式。
主要是为了防止一个类实例化多个对象造成数据不一致问题或者造成资源消耗问题(构建过程中的时间消耗、内存消耗)
new关键字直接创建对象。饿汉:
在类加载时就立即创建单例对象,并将其存储在静态成员变量中。
优点:类对象的创建特别快速,因为类的加载是一个比较靠前的阶段。 线程安全
缺点:创建后不使用,就会有长时间占用内存资源。
class Singleton { //1.构造器私有化,只能在内部new对象 private Singleton(){ } //2.内部实例化 private final static Singleton instance =new Singleton(); //3.提供get方法供外部使用,返回实例对象 public static Singleton getInstance(){ return instance; } }
懒汉:
单例实例在第一次被使用时才进行初始化
优点:真正需要使用某个类的实例的时候,才会创建,这样不会造成资源的浪费
缺点:使用了锁机制,第一次使用时候,多一次构造时间。
class Singleton { private: static Singleton* m_instance; Singleton(){} public: static Singleton* getInstance(); }; Singleton* Singleton::getInstance() { if(NULL == m_instance) { Lock();//借用其它类来实现,如boost if(NULL == m_instance) { m_instance = new Singleton; } UnLock(); } return m_instance; }
融入模板
#pragma once #include <mutex> template <class T> class Singleton{ public: static T* getInstance() { if (_singleton == nullptr) { std::lock_guard<std::recursive_mutex> lock(_mtx); if (_singleton == nullptr) _singleton = new T(); } return _singleton; } static void destroyInstance() { std::lock_guard<std::recursive_mutex> lock(_mtx); if (_singleton != nullptr) delete _singleton; _singleton = nullptr; } private: Singleton() {} virtual ~Singleton() {} private: static std::recursive_mutex _mtx; static T* _singleton; }; template <class T> std::recursive_mutex Singleton<T>::_mtx; template <class T> T* Singleton<T>::_singleton = nullptr; #define SINGLETON_CLASS(T) friend class Singleton<T>;
使用方式
class A { SINGLETON_CLASS(A) public: void func(){} private: A(){} ~A(){} }; int main(){ Singleton<A>::getInstance->func(); }
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。