能否给出更多现代C++架构设计模式?

好的,以下是几种现代C++中常见且实用的架构设计模式,结合了C++11/14/17等新特性:


1. 资源管理(RAII)

核心思想 :通过对象的生命周期管理资源(如内存、文件句柄、网络连接),确保资源自动释放。
现代实现:

  • 使用智能指针:std::unique_ptr、std::shared_ptr
  • 结合移动语义(std::move)优化所有权转移
cpp 复制代码
class FileHandler {
public:
    FileHandler(const std::string& path) : file_(std::make_unique<std::ifstream>(path)) {
        if (!file_->is_open()) throw std::runtime_error("File open failed");
    }
    // 自动关闭文件(析构时)
private:
    std::unique_ptr<std::ifstream> file_;
};

2. 策略模式(Strategy)

核心思想 :将算法抽象为接口,通过组合动态替换行为。
现代优化:

  • 使用std::function和Lambda替代传统接口类
  • 减少虚函数开销
cpp 复制代码
class Sorter {
public:
    using SortStrategy = std::function<void(std::vector<int>&)>;
    explicit Sorter(SortStrategy strategy) : strategy_(std::move(strategy)) {}
    void sort(std::vector<int>& data) { strategy_(data); }
private:
    SortStrategy strategy_;
};

// 使用Lambda定义策略
auto quick_sort = [](auto& data) { /* 快速排序实现 */ };
Sorter sorter(quick_sort);

3. 工厂模式(Factory)

核心思想 :封装对象创建逻辑,降低耦合。
现代扩展:

  • 结合std::variant或std::any支持多态返回
  • 使用std::make_unique避免裸指针
cpp 复制代码
class ShapeFactory {
public:
    enum class Type { Circle, Rectangle };
    std::unique_ptr<Shape> create(Type type) {
        switch (type) {
            case Type::Circle:     return std::make_unique<Circle>();
            case Type::Rectangle:  return std::make_unique<Rectangle>();
            default:               return nullptr;
        }
    }
};

4. 观察者模式(Observer)

核心思想 :定义一对多的依赖关系,当对象状态变化时自动通知依赖项。
现代优化:

  • 使用std::function和信号槽库(如Boost.Signals2)
  • 避免继承链
cpp 复制代码
class EventDispatcher {
public:
    using Listener = std::function<void(const Event&)>;
    void addListener(Listener listener) { listeners_.push_back(std::move(listener)); }
    void notify(const Event& event) {
        for (auto& listener : listeners_) listener(event);
    }
private:
    std::vector<Listener> listeners_;
};

5. 依赖注入(Dependency Injection)

核心思想 :通过外部传入依赖对象,提高模块可测试性和灵活性。
现代实践:

  • 结合构造函数或Setter注入
  • 使用std::shared_ptr管理共享依赖
cpp 复制代码
class DatabaseService {
public:
    explicit DatabaseService(std::shared_ptr<IDatabase> db) : db_(std::move(db)) {}
    void saveData(const Data& data) { db_->write(data); }
private:
    std::shared_ptr<IDatabase> db_;
};

6. 状态模式(State)

核心思想 :将状态行为封装在独立类中,通过上下文切换状态。
现代技巧:

  • 使用std::unique_ptr管理状态对象
  • 结合enum class明确状态类型
cpp 复制代码
class StateContext {
public:
    void setState(std::unique_ptr<State> new_state) {
        state_ = std::move(new_state);
    }
    void execute() { state_->handle(*this); }
private:
    std::unique_ptr<State> state_;
};

总结

现代C++设计模式的核心在于:

  1. 利用智能指针管理资源与生命周期
  2. 优先组合而非继承 (如std::function替代虚函数)
  3. 结合新标准特性(移动语义、Lambda、类型安全容器)
  4. 强调类型安全与零开销抽象

实际应用中需根据场景灵活组合模式,避免过度设计。

相关推荐
多加点辣也没关系1 小时前
JavaScript|第41章:性能优化实战
开发语言·javascript·性能优化
Resean02231 小时前
架构设计系列(十六):DDD 与代码架构
java·开发语言·架构
学长毕设2 小时前
基于SpringBoot 车辆租赁系统平台-附源码
java·spring boot·后端
码途行者2 小时前
每天10分钟学Go:第22课 自定义错误
开发语言·后端·golang
23图2 小时前
C 语言开散列表(拉链法)拆解:链挂得没错,key=-1 会去读 T[-1]
c语言·开发语言·散列表
feixing_fx3 小时前
解构与展开:可读性和性能的取舍
开发语言·前端·javascript·前端框架
小飞在努力3 小时前
【实现负载均匀在线判题③】从零散模块到统一,编译运行全链路封装
c语言·开发语言·c++·笔记
Flynt4 小时前
Spring AI Alibaba 真停更了?我把它的 GitHub 翻了个底朝天
java·spring·开源
饮水桶_T7 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
她的男孩7 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎