行业知识
【C++ 23种设计模式】
2026-11-24 21:39:00
来源:互联网转载
C++ 23种设计模式
- ■ 创建型模式(5种)
- ■ 工厂模式
- ■ 抽象工厂模式
- ■ 原型模式
- ■ 单例模式
- ■ 第一种:单线程(懒汉)
- ■ 第二种:多线程(互斥量实现锁+懒汉)
- ■ 第三种:多线程(const static+饿汉)(还要继续了解)
- ■ 建造者模式
- ■ 结构型模式(7种)
- ■ 适配器模式
- ■ 桥接模式
- ■ 组合实体模式
- ■ 装饰器模式
- ■ 外观模式
- ■ 享元模式
- ■ 代理模式
- ■ 行为型模式(11种)
- ■ 责任链模式
- ■ 中介者模式
- ■ 策略模式
- ■ 模板模式
- ■ 状态模式
- ■ 观察者模式
- ■ 备忘录模式
- ■ 命令模式
- ■ 访问者模式
- ■ 解释器模式
- �� 迭代器模式
■ 创建型模式(5种)
■ 工厂模式
示例一:
()#include#includeusing namespace std;enum CTYPE{COREA,COREB};//定义一个基类单核class SingleCore {public:virtual void show() = 0;};//单核Aclass SingleCoreA:public SingleCore{public:void show() {cout public:void show() {cout public://基类的对象指针指向子类的对象,也就是多态SingleCore* CreateSingleCore(CTYPE ctype){//工厂内部判断if (ctype == COREA){//生产核Areturn new SingleCoreA();}else if (ctype == COREB){//生产核Breturn new SingleCoreB();}else {return NULL;}}};int main() {Factory* factor = new Factory();factor-CreateSingleCore(COREA)-show();getchar();return 0;}private: static Singleton1* m_pInstance1;//需要的时候才创建,懒汉 //利用static关键字的特性,不属于任何类,整个类只有一个 Singleton1();public: static Singleton1* GetInstance1(); static void DestroyInstance1();};Singleton1::Singleton1(){ cout return m_pInstance1;}void Singleton1::DestroyInstance1(){ if (m_pInstance1 != nullptr) { delete m_pInstance1; m_pInstance1 = nullptr; }}//初始化一个对象Singleton1* Singleton1::m_pInstance1 = new Singleton1();//单线程下多次获取实例void test1(){ Singleton1* singletoObj1 = Singleton1::GetInstance1(); cout private: Singleton2(); static Singleton2* m_pInstance2; static mutex m_mutex;//互斥量public: static Singleton2* GetInstance2(); static void DestroyInstance2();};Singleton2::Singleton2(){ cout if (m_pInstance2 == nullptr) { cout m_pInstance2 = new Singleton2(); } cout if (m_pInstance2 != nullptr) { delete m_pInstance2; m_pInstance2 = nullptr; }}//静态成员变量的定义Singleton2* Singleton2::m_pInstance2 = nullptr;//懒汉式的写法mutex Singleton2::m_mutex;//常见一个实例对象,给下面的多线程调用void print_singleton_instance(){ Singleton2* singletonObj2 = Singleton2::GetInstance2(); cout vector //十个线程都指向同一个静态变量的地址 threads.push_back(thread(print_singleton_instance)); } for (auto& thr : threads) { thr.join(); }}private: Singleton3(){} static const Singleton3* m_pInstance3;public: static Singleton3* GetInstance3(); static void DestroyInstance3();};Singleton3* Singleton3::GetInstance3(){ //这个函数的返回值如果变化曾const static属性,就不用进行const_cast return const_cast if (m_pInstance3 != nullptr) { delete m_pInstance3; m_pInstance3 = nullptr; }}//静态成员变量的定义const Singleton3* Singleton3::m_pInstance3 = new Singleton3();//饿汉式的写法//常见一个实例对象,给下面的多线程调用void print_singleton_instance3(){ Singleton3* singletonObj3 = Singleton3::GetInstance3(); cout vector //十个线程都指向同一个静态变量的地址 threads.push_back(thread(print_singleton_instance3)); } for (auto& thr : threads) { thr.join(); }}
上一篇:怎么租赁网易服务器?
下一篇:怎么查解除劳动合同是否备案