有哪些常见的架构设计模式在现代C++中应用

在现代C++中,以下架构设计模式被广泛应用:


1. 工厂模式

核心思想 :封装对象的创建逻辑,通过统一接口生成不同类型对象。
现代实现

  • 使用智能指针(如 std::unique_ptr)管理资源
  • 结合模板或 std::function 实现泛型工厂
cpp 复制代码
class IProduct {
public:
    virtual ~IProduct() = default;
    virtual void operation() = 0;
};

template <typename T>
std::unique_ptr<IProduct> createProduct() {
    return std::make_unique<T>();
}

2. RAII(资源获取即初始化)

核心思想 :通过对象生命周期自动管理资源(内存、文件句柄等)。
现代特性

  • 智能指针(std::unique_ptr, std::shared_ptr
  • 移动语义(避免深拷贝)
cpp 复制代码
class FileHandler {
public:
    FileHandler(const std::string& path) : handle(openFile(path)) {}
    ~FileHandler() { closeFile(handle); }
    // 禁用拷贝,启用移动
    FileHandler(FileHandler&&) = default;
private:
    HandleType handle;
};

3. 观察者模式

核心思想 :对象状态变化时自动通知依赖它的对象。
现代优化

  • 使用 std::function 替代虚函数接口
  • 结合 std::vector 存储观察者
cpp 复制代码
class Subject {
public:
    void addObserver(std::function<void()> obs) {
        observers.push_back(obs);
    }
    void notify() {
        for (auto& obs : observers) obs();
    }
private:
    std::vector<std::function<void()>> observers;
};

4. 策略模式

核心思想 :将算法封装为独立对象,支持运行时切换。
现代实现

  • 通过 std::function 和 Lambda 表达式简化策略定义
cpp 复制代码
class Context {
public:
    void setStrategy(std::function<void()> strategy) {
        this->strategy = strategy;
    }
    void execute() { strategy(); }
private:
    std::function<void()> strategy;
};

// 使用示例
Context ctx;
ctx.setStrategy([] { /* 策略A逻辑 */ });
ctx.execute();

5. 单例模式

核心思想 :确保类仅有一个实例,并提供全局访问点。
线程安全改进

  • C++11 后的 std::call_once 保证初始化原子性
cpp 复制代码
class Singleton {
public:
    static Singleton& getInstance() {
        static std::once_flag flag;
        std::call_once(flag, [] { instance.reset(new Singleton); });
        return *instance;
    }
private:
    static std::unique_ptr<Singleton> instance;
    Singleton() = default;
};

6. 适配器模式

核心思想 :转换不兼容接口为目标接口。
现代应用

  • 结合模板实现泛型适配
  • 使用 std::bind 包装旧接口
cpp 复制代码
class LegacySystem {
public:
    void legacyOperation(int x) { /*...*/ }
};

class Adapter {
public:
    Adapter(LegacySystem& legacy) : adaptee(legacy) {}
    void modernOperation() {
        std::bind(&LegacySystem::legacyOperation, &adaptee, 42)();
    }
private:
    LegacySystem& adaptee;
};

总结

现代C++通过以下特性优化传统设计模式:

  1. 智能指针(自动资源管理)
  2. Lambda 和 std::function(减少虚函数开销)
  3. 移动语义(提升性能)
  4. 模板(增强泛化能力)

选择模式时需结合具体场景,避免过度设计。

相关推荐
倒头就睡的小比特12 小时前
算法竞赛C++常用的STL
c++·算法
weilx123412 小时前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!12 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读13 小时前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛14 小时前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车14 小时前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光14 小时前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·15 小时前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁15 小时前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven15 小时前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法