C++的设计模式

news/2025/2/24 17:43:53

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://www.niftyadmin.cn/n/5864662.html

相关文章

【深度学习】手写数字识别任务

数字识别是计算机从纸质文档、照片或其他来源接收、理解并识别可读的数字的能力&#xff0c;目前比较受关注的是手写数字识别。手写数字识别是一个典型的图像分类问题&#xff0c;已经被广泛应用于汇款单号识别、手写邮政编码识别等领域&#xff0c;大大缩短了业务处理时间&…

Linux 命令大全完整版(11)

5.文件管理命令 diff&#xff08;differential&#xff09; 功能说明&#xff1a;比较文件的差异。语  法&#xff1a;diff [-abBcdefHilnNpPqrstTuvwy][-<行数>][-C <行数>][-D <巨集名称>][-I <字符或字符串>][-S <文件>][-W <宽度>…

DeepSeek本地搭建 和 Android

DeepSeek 搭建和 Android 文章目录 DeepSeek 搭建和 Android一、前言二、DeepSeek 本地环境ollama搭建1、软件下载网址&#xff1a;2、Ollama的安装3、配置算法模型和使用qwen2 模型使用&#xff0c; 三、Android Studio 和 DeepSeek四、其他1、Deepseek 使用小结(1) 网页版本可…

通俗理解Test time Scaling Law、RL Scaling Law和预训练Scaling Law

一、Scaling Law解释 1、预训练阶段的Scaling Law&#xff08;打地基阶段&#xff09; 通俗解释&#xff1a;就像建房子时&#xff0c;地基越大、材料越多、施工时间越长&#xff0c;房子就能盖得越高越稳。 核心&#xff1a;通过堆资源&#xff08;算力、数据、模型参数&am…

Express + MongoDB 实现在筛选时间段中用户名的模糊查询

使用 $gte&#xff08;大于等于&#xff09;和 $lte&#xff08;小于等于&#xff09;操作符构建时间段查询条件。使用 $regex 操作符进行模糊查询&#xff0c;$options: i 表示不区分大小写。使用 $and 操作符将它们组合起来。 // 处理查询的路由app.get("/users",…

[设计模式] Builder 建造者模式

目录 意图 问题 解决 Applying the Builder pattern 主管 结构 伪代码 生成器模式适合应用场景 实现方法 生成器模式优缺点 与其他模式的关系 C代码 main.cc&#xff1a;概念示例 Output.txt&#xff1a;执行结果 意图 Builder 是一种创建性设计模式&#xff0c…

C语言【指针篇】(一)

前言 指针基础概念理解&#xff0c;从底层出发理解指针 C语言【指针篇】&#xff08;一&#xff09; 前言正文1. 内存和地址1.1 内存1.2 究竟该如何理解编址 2. 指针变量和地址2.1 取地址操作符(&)2.2 指针变量和解引用操作符(*)2.3 指针变量的大小 3. 指针变量类型的意义…

Qt 中集成mqtt协议

一&#xff0c;引入qmqtt 库 我是将整个头文件/源文件都添加到了工程中进行编译&#xff0c;这样 跨平台时 方便&#xff0c;直接编译就行了。 原始仓库路径&#xff1a;https://github.com/emqx/qmqtt/tree/master 二&#xff0c;使用 声明一个单例类&#xff0c;将订阅到…