当前位置: 首页 > news >正文

C++的设计模式

1. 创建型模式

单例模式 (Singleton)
  • 意图:确保类仅有一个实例,并提供全局访问点。(常见的日志类)
  • 实现
    class Singleton {
    private:
        static Singleton* instance;
        Singleton() {} // 私有构造函数
    public:
        static Singleton* getInstance() {
            if (!instance) {
                instance = new Singleton();
            }
            return instance;
        }
        // 删除拷贝构造和赋值
        Singleton(const Singleton&) = delete;
        void operator=(const Singleton&) = delete;
    };
    Singleton* Singleton::instance = nullptr;
    
  • 线程安全:需加锁(如std::mutex)或使用C++11的std::call_once
工厂模式 (Factory)
  • 简单工厂:根据参数创建不同对象。
    class Product {
    public:
        virtual void use() = 0;
    };
    class ConcreteProductA : public Product { /*...*/ };
    class Factory {
    public:
        static Product* createProduct(const std::string& type) {
            if (type == "A") return new ConcreteProductA();
            // ...
        }
    };
    
  • 抽象工厂:创建相关对象族。
    class AbstractFactory {
    public:
        virtual Button* createButton() = 0;
        virtual TextBox* createTextBox() = 0;
    };
    class WinFactory : public AbstractFactory { /*...*/ };
    

2. 结构型模式

适配器模式 (Adapter)
  • 对象适配器:持有被适配对象的实例。
    class Target {
    public:
        virtual void request() = 0;
    };
    class Adaptee { public: void specificRequest() {} };
    class Adapter : public Target {
        Adaptee* adaptee;
    public:
        Adapter(Adaptee* a) : adaptee(a) {}
        void request() override { adaptee->specificRequest(); }
    };
    
装饰器模式 (Decorator)
  • 动态添加职责
    class Component { public: virtual void operation() = 0; };
    class ConcreteComponent : public Component { /*...*/ };
    class Decorator : public Component {
        Component* component;
    public:
        Decorator(Component* c) : component(c) {}
        void operation() override { component->operation(); }
    };
    class ConcreteDecorator : public Decorator {
        void addedBehavior() { /*...*/ }
    public:
        void operation() override {
            Decorator::operation();
            addedBehavior();
        }
    };
    

3. 行为型模式

观察者模式 (Observer)
  • 实现松散耦合
    class Observer {
    public:
        virtual void update(const std::string& msg) = 0;
    };
    class Subject {
        std::vector<Observer*> observers;
    public:
        void attach(Observer* o) { observers.push_back(o); }
        void notify(const std::string& msg) {
            for (auto o : observers) o->update(msg);
        }
    };
    
策略模式 (Strategy)
  • 运行时切换算法
    class Strategy {
    public:
        virtual void execute() = 0;
    };
    class Context {
        Strategy* strategy;
    public:
        void setStrategy(Strategy* s) { strategy = s; }
        void execute() { strategy->execute(); }
    };
    

4. C++特定注意事项

  • 内存管理:优先使用智能指针(std::shared_ptr, std::unique_ptr)避免泄漏。
  • 多线程:单例模式需双重检查锁定或局部静态变量(C++11后线程安全)。
  • 性能:虚函数可能引入开销,需权衡设计灵活性与性能。
  • 模板:替代某些模式(如策略模式可通过模板在编译时绑定)。

总结

  • 选择模式的原则:优先简单性,避免过度设计。
  • 模式组合:如工厂+单例创建全局唯一对象,观察者+组合构建事件系统。
  • 语言特性结合:利用RAII、模板、移动语义等增强实现。

文章转载自:
http://caiaphas.hyyxsc.cn
http://accumulator.hyyxsc.cn
http://adios.hyyxsc.cn
http://catechol.hyyxsc.cn
http://britishly.hyyxsc.cn
http://anthroponym.hyyxsc.cn
http://ascendent.hyyxsc.cn
http://ballroom.hyyxsc.cn
http://autoaggressive.hyyxsc.cn
http://autoeciously.hyyxsc.cn
http://anestrous.hyyxsc.cn
http://birthstone.hyyxsc.cn
http://chinee.hyyxsc.cn
http://antiderivative.hyyxsc.cn
http://berascal.hyyxsc.cn
http://butternut.hyyxsc.cn
http://alguazil.hyyxsc.cn
http://bitterly.hyyxsc.cn
http://adjectival.hyyxsc.cn
http://antigua.hyyxsc.cn
http://aftersensation.hyyxsc.cn
http://appreciate.hyyxsc.cn
http://acari.hyyxsc.cn
http://carbohydrate.hyyxsc.cn
http://abstracted.hyyxsc.cn
http://biographically.hyyxsc.cn
http://bullshot.hyyxsc.cn
http://aviation.hyyxsc.cn
http://cellblock.hyyxsc.cn
http://burnoose.hyyxsc.cn
http://www.dtcms.com/a/34675.html

相关文章:

  • 虚拟机科普+虚拟机的安装
  • langchain学习笔记之基于RAG实现文档问答
  • leetcode_位运算 2206. 将数组划分成相等数对
  • Python 入门教程(2)搭建环境 | 2.3、VSCode配置Python开发环境
  • 【新人系列】Golang 入门(一):基础介绍
  • 【AI学习笔记】2月10日李飞飞巴黎AI峰会演讲:探索 AI 的历史、现状与未来
  • Python CNN基于深度学习的轴承故障智能检测平台
  • JavaScript实现一个函数,找出数组中重复出现次数最多的元素。
  • 垂类大模型微调(一):认识LLaMA-Factory
  • 芯谷D2761:为扬声器保护而生的音频限幅器
  • [Android]AppCompatEditText限制最多只能输入两位小数
  • 在运维工作中,硬盘满了,新买了一块,如何扩容?
  • Linux按照日期定时删除elasticsearch索引
  • 适合开发独立数据库SaaS系统的编程语言选择
  • 解决ExtJS 6/7无限滚动表格/列表(infinite: true)无法在触屏Windows浏览器上触摸滚动
  • mysql的源码包安装
  • 【redis】redis内存管理,过期策略与淘汰策略
  • QT串口通信之二,实现单个温湿度传感器数据的采集(采用Qt-modbus实现)
  • 【深度学习】Transformer 的常见的位置编码有哪些
  • 4. MySQL 逻辑架构说明
  • k8s集群部署
  • 深入解析JVM垃圾回收机制
  • podman加速器配置,harbor镜像仓库部署
  • QT(5.15)之QGC(4.4)安装教程
  • springboot3整合knife4j详细版,包会!(不带swagger2玩)
  • 讯飞离线唤醒+离线Vosk识别+DeepSeek大模型+讯飞离线合成持续优化,无限可能~
  • 【Qt】可爱的窗口关闭确认弹窗实现
  • ZT9 游游的字母翻倍
  • 开源AI网络爬虫工具Crawl4AI
  • vue3学习--Vue3与2的区别