title: 单例模式
categories: [设计模式]
tags: [单例模式]
我的私人博客
饿汉模式#include懒汉模式 线程安全(双重校验锁)using namespace std; class HungrySingleton{ private: int count = 0; static HungrySingleton* instance; HungrySingleton() = default; public: ~HungrySingleton() = default; static HungrySingleton* getInstance(){ return instance; } void showMessage(){ cout< showMessage(); return 0; }
#include线程安全(局部静态变量)#include using namespace std; class LazySingleton{ private: static LazySingleton* instance; static mutex _lock; int count = 1; LazySingleton() = default; public: ~LazySingleton() = default; static LazySingleton* getInstance(){ if(instance==nullptr){ lock_guard locker(_lock); if(instance== nullptr){ instance = new LazySingleton; } } return instance; } void showMessage(){ cout< showMessage(); return 0; }
#includeclass LazySingleton{ private: int count = 1; LazySingleton() = default; public: ~LazySingleton() = default; static LazySingleton* getInstance(){ static LazySingleton instance; return &instance; } void showMessage(){ cout< showMessage(); return 0; }



