有哪些常见的架构设计模式在现代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. 模板(增强泛化能力)

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

相关推荐
郝学胜_神的一滴11 小时前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
见过夏天1 天前
C++ 基础入门完全指南
c++
用户805533698032 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK3 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境3 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境3 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴4 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境6 天前
C++ 的Eigen 库全解析
c++
卷无止境6 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴6 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake