跳到主要内容
极客日志极客日志
首页博客AI提示词GitHub精选代理工具
搜索
|注册
博客列表
C++

C++ 设计模式核心概览与实战实现

C++ 设计模式涵盖创建型、结构型和行为型三大类共 23 种方案。单例、工厂、观察者等高频模式的代码实现与适用场景,强调解耦与复用原则。内容包含完整类定义示例,帮助开发者构建高可维护性系统。

ArchDesign发布于 2026/3/20更新于 2026/4/252 浏览

C++ 设计模式核心概览与实战实现

设计模式是解决特定软件设计问题的可复用方案。在 C++ 中,它们主要分为三大类:创建型、结构型和行为型。以下整理了 23 种常见模式的分类及代码示例,重点展示常用模式的实现细节。

一、创建型模式(5 个)

1. 单例模式(Singleton)

适用场景:全局唯一实例,如配置管理器、日志管理器。

// 假设已引入 iostream 和 using namespace std;
class Singleton {
private:
    static Singleton* instance;
    Singleton() {} // 私有构造函数
public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
    // 删除拷贝构造和赋值操作符,防止复制
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
};
Singleton* Singleton::instance = nullptr;
2. 工厂方法模式(Factory Method)

适用场景:对象创建解耦,易于扩展新类型。

class Product {
public:
    virtual ~Product() {}
    virtual void operation() = 0;
};

class ConcreteProductA : public Product {
public:
    void operation() override {
        std::cout << "Product A operation" << std::endl;
    }
};

class Creator {
public:
    virtual ~Creator() {}
    virtual Product* factoryMethod() = 0;
};

class ConcreteCreatorA : public Creator {
public:
    Product* factoryMethod() override {
        return new ConcreteProductA();
    }
};
3. 抽象工厂模式(Abstract Factory)

适用场景:创建一系列相关或依赖的对象,无需指定具体类。

class AbstractProductA {
public:
    virtual ~AbstractProductA() {}
    virtual void operationA() = 0;
};

class AbstractProductB {
public:
    virtual ~AbstractProductB() {}
    virtual void operationB() = 0;
};

class AbstractFactory {
public:
    virtual AbstractProductA* createProductA() = 0;
    virtual AbstractProductB* createProductB() = 0;
};

class ConcreteFactory1 : public AbstractFactory {
public:
    AbstractProductA* createProductA() override { return new ConcreteProductA1(); }
    AbstractProductB* createProductB() override { return new ConcreteProductB1(); }
};
4. 建造者模式(Builder)

适用场景:构建复杂对象,步骤分离。

class Product {
private:
    std::string partA;
    std::string partB;
public:
    void setPartA(const std::string& a) { partA = a; }
    void setPartB(const std::string& b) { partB = b; }
};

class Builder {
public:
    virtual ~Builder() {}
    virtual void buildPartA() = 0;
    virtual void buildPartB() = 0;
    virtual Product* getResult() = 0;
};

class Director {
private:
    Builder* builder;
public:
    Director(Builder* b) : builder(b) {}
    void construct() {
        builder->buildPartA();
        builder->buildPartB();
    }
};
5. 原型模式(Prototype)

适用场景:通过复制现有对象来创建新对象。

class Prototype {
public:
    virtual ~Prototype() {}
    virtual Prototype* clone() const = 0;
    virtual void print() const = 0;
};

class ConcretePrototype : public Prototype {
private:
    int data;
public:
    ConcretePrototype(int d) : data(d) {}
    Prototype* clone() const override { return new ConcretePrototype(*this); }
    void print() const override {
        std::cout << "Data: " << data << std::endl;
    }
};

二、结构型模式(7 个)

6. 适配器模式(Adapter)

适用场景:接口转换,使不兼容的接口可以协同工作。

class Target {
public:
    virtual ~Target() {}
    virtual void request() {
        std::cout << "Target request" << std::endl;
    }
};

class Adaptee {
public:
    void specificRequest() {
        std::cout << "Adaptee specific request" << std::endl;
    }
};

class Adapter : public Target {
private:
    Adaptee* adaptee;
public:
    Adapter(Adaptee* a) : adaptee(a) {}
    void request() override {
        adaptee->specificRequest();
    }
};
7. 桥接模式(Bridge)

适用场景:将抽象部分与实现部分分离,使它们可以独立变化。

class Implementor {
public:
    virtual ~Implementor() {}
    virtual void operationImpl() = 0;
};

class Abstraction {
protected:
    Implementor* impl;
public:
    Abstraction(Implementor* i) : impl(i) {}
    virtual ~Abstraction() {}
    virtual void operation() {
        impl->operationImpl();
    }
};
8. 组合模式(Composite)

适用场景:将对象组合成树形结构以表示'部分 - 整体'的层次结构。

class Component {
public:
    virtual ~Component() {}
    virtual void operation() = 0;
    virtual void add(Component*) {}
    virtual void remove(Component*) {}
    virtual Component* getChild(int) { return nullptr; }
};

class Leaf : public Component {
public:
    void operation() override {
        std::cout << "Leaf operation" << std::endl;
    }
};

class Composite : public Component {
private:
    std::vector<Component*> children;
public:
    void operation() override {
        std::cout << "Composite operation" << std::endl;
        for (auto child : children) {
            child->operation();
        }
    }
    void add(Component* c) override {
        children.push_back(c);
    }
};
9. 装饰器模式(Decorator)

适用场景:动态地给一个对象添加一些额外的职责。

class Component {
public:
    virtual ~Component() {}
    virtual void operation() = 0;
};

class ConcreteComponent : public Component {
public:
    void operation() override {
        std::cout << "ConcreteComponent operation" << std::endl;
    }
};

class Decorator : public Component {
protected:
    Component* component;
public:
    Decorator(Component* c) : component(c) {}
    void operation() override {
        component->operation();
    }
};

class ConcreteDecorator : public Decorator {
public:
    ConcreteDecorator(Component* c) : Decorator(c) {}
    void operation() override {
        Decorator::operation();
        addedBehavior();
    }
    void addedBehavior() {
        std::cout << "Added behavior" << std::endl;
    }
};
10. 外观模式(Facade)

适用场景:为子系统中的一组接口提供一个一致的界面。

class SubsystemA {
public:
    void operationA() {
        std::cout << "Subsystem A operation" << std::endl;
    }
};

class SubsystemB {
public:
    void operationB() {
        std::cout << "Subsystem B operation" << std::endl;
    }
};

class Facade {
private:
    SubsystemA* a;
    SubsystemB* b;
public:
    Facade() : a(new SubsystemA()), b(new SubsystemB()) {}
    void operation() {
        a->operationA();
        b->operationB();
    }
};
11. 享元模式(Flyweight)

适用场景:大量细粒度对象的共享,减少内存占用。

class Flyweight {
public:
    virtual ~Flyweight() {}
    virtual void operation(int extrinsicState) = 0;
};

class ConcreteFlyweight : public Flyweight {
private:
    int intrinsicState;
public:
    ConcreteFlyweight(int state) : intrinsicState(state) {}
    void operation(int extrinsicState) override {
        std::cout << "Intrinsic: " << intrinsicState << ", Extrinsic: " << extrinsicState << std::endl;
    }
};

class FlyweightFactory {
private:
    std::unordered_map<int, Flyweight*> flyweights;
public:
    Flyweight* getFlyweight(int key) {
        if (flyweights.find(key) == flyweights.end()) {
            flyweights[key] = new ConcreteFlyweight(key);
        }
        return flyweights[key];
    }
};
12. 代理模式(Proxy)

适用场景:访问控制、延迟加载等。

class Subject {
public:
    virtual ~Subject() {}
    virtual void request() = 0;
};

class RealSubject : public Subject {
public:
    void request() override {
        std::cout << "RealSubject request" << std::endl;
    }
};

class Proxy : public Subject {
private:
    RealSubject* realSubject;
public:
    Proxy() : realSubject(nullptr) {}
    void request() override {
        if (realSubject == nullptr) {
            realSubject = new RealSubject();
        }
        realSubject->request();
    }
};

三、行为型模式(11 个)

13. 责任链模式(Chain of Responsibility)

适用场景:多个对象处理请求,直到有一个处理它。

class Handler {
protected:
    Handler* successor;
public:
    Handler() : successor(nullptr) {}
    virtual ~Handler() {}
    void setSuccessor(Handler* s) { successor = s; }
    virtual void handleRequest(int request) = 0;
};

class ConcreteHandler1 : public Handler {
public:
    void handleRequest(int request) override {
        if (request < 10) {
            std::cout << "Handler1 handled request " << request << std::endl;
        } else if (successor != nullptr) {
            successor->handleRequest(request);
        }
    }
};
14. 命令模式(Command)

适用场景:请求封装为对象,支持撤销/重做。

class Receiver {
public:
    void action() {
        std::cout << "Receiver action" << std::endl;
    }
};

class Command {
public:
    virtual ~Command() {}
    virtual void execute() = 0;
};

class ConcreteCommand : public Command {
private:
    Receiver* receiver;
public:
    ConcreteCommand(Receiver* r) : receiver(r) {}
    void execute() override {
        receiver->action();
    }
};

class Invoker {
private:
    Command* command;
public:
    void setCommand(Command* c) { command = c; }
    void executeCommand() {
        command->execute();
    }
};
15. 解释器模式(Interpreter)

适用场景:定义语言的文法,并建立解释器。

class Context {
    // 上下文信息
};

class Expression {
public:
    virtual ~Expression() {}
    virtual bool interpret(Context& context) = 0;
};

class TerminalExpression : public Expression {
public:
    bool interpret(Context& context) override {
        // 终结符解释逻辑
        return true;
    }
};
16. 迭代器模式(Iterator)

适用场景:顺序访问聚合对象的元素,而不暴露其内部表示。

template<typename T>
class Iterator {
public:
    virtual ~Iterator() {}
    virtual T next() = 0;
    virtual bool hasNext() = 0;
};

template<typename T>
class ConcreteIterator : public Iterator<T> {
private:
    std::vector<T> collection;
    size_t position;
public:
    ConcreteIterator(const std::vector<T>& col) : collection(col), position(0) {}
    T next() override { return collection[position++]; }
    bool hasNext() override { return position < collection.size(); }
};
17. 中介者模式(Mediator)

适用场景:用一个中介对象来封装一系列的对象交互。

class Colleague;
class Mediator {
public:
    virtual ~Mediator() {}
    virtual void notify(Colleague* sender, std::string event) = 0;
};

class Colleague {
protected:
    Mediator* mediator;
public:
    Colleague(Mediator* m = nullptr) : mediator(m) {}
    void setMediator(Mediator* m) { mediator = m; }
};

class ConcreteColleague1 : public Colleague {
public:
    void doSomething() {
        // ... 自己的逻辑
        mediator->notify(this, "event1");
    }
};
18. 备忘录模式(Memento)

适用场景:在不破坏封装性的前提下,捕获一个对象的内部状态。

class Memento {
private:
    std::string state;
public:
    Memento(const std::string& s) : state(s) {}
    std::string getState() const { return state; }
};

class Originator {
private:
    std::string state;
public:
    void setState(const std::string& s) { state = s; }
    std::string getState() const { return state; }
    Memento* createMemento() { return new Memento(state); }
    void restoreMemento(Memento* m) { state = m->getState(); }
};
19. 观察者模式(Observer)

适用场景:事件处理、消息通知系统。

class Observer {
public:
    virtual ~Observer() {}
    virtual void update(float temperature) = 0;
};

class Subject {
private:
    std::vector<Observer*> observers;
public:
    void attach(Observer* o) { observers.push_back(o); }
    void detach(Observer* o) { /* 移除观察者逻辑 */ }
    void notify(float temperature) {
        for (auto observer : observers) {
            observer->update(temperature);
        }
    }
};

class ConcreteObserver : public Observer {
public:
    void update(float temperature) override {
        std::cout << "Temperature updated: " << temperature << std::endl;
    }
};
20. 状态模式(State)

适用场景:允许对象在内部状态改变时改变其行为。

class Context;
class State {
public:
    virtual ~State() {}
    virtual void handle(Context* context) = 0;
};

class Context {
private:
    State* state;
public:
    Context(State* s) : state(s) {}
    void setState(State* s) { state = s; }
    void request() { state->handle(this); }
};

class ConcreteStateA : public State {
public:
    void handle(Context* context) override;
};
21. 策略模式(Strategy)

适用场景:算法封装,运行时切换。

class Strategy {
public:
    virtual ~Strategy() {}
    virtual void algorithm() = 0;
};

class ConcreteStrategyA : public Strategy {
public:
    void algorithm() override {
        std::cout << "Strategy A algorithm" << std::endl;
    }
};

class Context {
private:
    Strategy* strategy;
public:
    Context(Strategy* s) : strategy(s) {}
    void setStrategy(Strategy* s) { strategy = s; }
    void executeStrategy() { strategy->algorithm(); }
};
22. 模板方法模式(Template Method)

适用场景:定义算法骨架,子类实现具体步骤。

class AbstractClass {
public:
    virtual ~AbstractClass() {}
    void templateMethod() {
        primitiveOperation1();
        primitiveOperation2();
    }
    virtual void primitiveOperation1() = 0;
    virtual void primitiveOperation2() = 0;
};

class ConcreteClass : public AbstractClass {
public:
    void primitiveOperation1() override {
        std::cout << "Concrete operation 1" << std::endl;
    }
    void primitiveOperation2() override {
        std::cout << "Concrete operation 2" << std::endl;
    }
};
23. 访问者模式(Visitor)

适用场景:在不修改各元素类的前提下,增加新的操作。

class ConcreteElementA;
class ConcreteElementB;
class Visitor {
public:
    virtual ~Visitor() {}
    virtual void visit(ConcreteElementA* element) = 0;
    virtual void visit(ConcreteElementB* element) = 0;
};

class Element {
public:
    virtual ~Element() {}
    virtual void accept(Visitor* visitor) = 0;
};

class ConcreteElementA : public Element {
public:
    void accept(Visitor* visitor) override { visitor->visit(this); }
    void operationA() {
        std::cout << "Operation A" << std::endl;
    }
};

四、学习建议与核心总结

在实际开发中,不必掌握所有 23 种模式,建议优先关注以下高频场景:

  1. 必须掌握的 5 个核心模式:

    • 单例模式:确保全局唯一实例。
    • 工厂方法模式:解耦对象创建过程。
    • 观察者模式:处理松耦合的事件通知。
    • 策略模式:灵活替换算法实现。
    • 装饰器模式:动态增强对象功能。
  2. 次常用的 5 个模式:

    • 适配器模式:解决接口不兼容问题。
    • 代理模式:控制访问或延迟初始化。
    • 模板方法模式:规范算法流程。
    • 命令模式:封装请求为对象。
    • 外观模式:简化复杂子系统调用。
  3. 实践心得:

    • 先从单例、工厂、观察者、策略开始理解模式思想。
    • 理解每种模式的应用场景比死记代码更重要。
    • 避免过度设计,只在必要时使用设计模式。
    • 结合 C++11/14/17 的现代特性(智能指针、lambda 等)可以简化某些模式的实现。

这些模式提供了经过验证的解决方案,能帮助你构建更灵活、可维护的软件系统。

目录

  1. C++ 设计模式核心概览与实战实现
  2. 一、创建型模式(5 个)
  3. 1. 单例模式(Singleton)
  4. 2. 工厂方法模式(Factory Method)
  5. 3. 抽象工厂模式(Abstract Factory)
  6. 4. 建造者模式(Builder)
  7. 5. 原型模式(Prototype)
  8. 二、结构型模式(7 个)
  9. 6. 适配器模式(Adapter)
  10. 7. 桥接模式(Bridge)
  11. 8. 组合模式(Composite)
  12. 9. 装饰器模式(Decorator)
  13. 10. 外观模式(Facade)
  14. 11. 享元模式(Flyweight)
  15. 12. 代理模式(Proxy)
  16. 三、行为型模式(11 个)
  17. 13. 责任链模式(Chain of Responsibility)
  18. 14. 命令模式(Command)
  19. 15. 解释器模式(Interpreter)
  20. 16. 迭代器模式(Iterator)
  21. 17. 中介者模式(Mediator)
  22. 18. 备忘录模式(Memento)
  23. 19. 观察者模式(Observer)
  24. 20. 状态模式(State)
  25. 21. 策略模式(Strategy)
  26. 22. 模板方法模式(Template Method)
  27. 23. 访问者模式(Visitor)
  28. 四、学习建议与核心总结
  • 💰 8折买阿里云服务器限时8折了解详情
  • 💰 8折买阿里云服务器限时8折购买
  • 🦞 5分钟部署阿里云小龙虾了解详情
  • 🤖 一键搭建Deepseek满血版了解详情
  • 一键打造专属AI 智能体了解详情
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog

更多推荐文章

查看全部
  • OpenClaw 系列 AI Agent 工具选型指南
  • Windows 系统 WSL2 部署 OpenClaw 实战指南
  • 归并排序实战:计算右侧小于当前元素个数与翻转对
  • Linux 初始网络(下):局域网通信与跨网段传输原理
  • 前端核心面试题与实战知识点梳理
  • 算法基础:滑动窗口技巧与经典例题解析
  • AI Agent 新范式:FastGPT 集成 MCP 协议构建工具增强智能体
  • C++ 二叉搜索树实现详解
  • 数据结构基础:顺序表详解与动态实现
  • Qwen3+Qwen Agent 智能体开发实战:接入 MCP 工具(一)
  • C++ 二叉搜索树(BST)原理及核心操作实现
  • 数据结构详解:顺序表原理与实现
  • OpenClaw 安装部署与渠道接入指南
  • Linux 基础 IO:深入理解文件描述符机制
  • Linux 文件描述符与重定向实战:从原理到 minishell 实现
  • DeepSeek 深度使用指南:提示词技巧与本地知识库搭建
  • C++ 继承:面向对象代码复用的核心机制
  • 深入剖析 Spring 框架:架构、缺陷与演进之路
  • 数据结构与算法:链表分类详解与双向链表初始化实现
  • LeetCode Hot 100 链表经典题目实战解析

相关免费在线工具

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online

  • HTML转Markdown

    将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online

  • JSON 压缩

    通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online

  • JSON美化和格式化

    将JSON字符串修饰为友好的可读格式。 在线工具,JSON美化和格式化在线工具,online