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

C++ 设计模式详解:创建型、结构型与行为型实战

综述由AI生成本文详细梳理了 C++ 中 23 种设计模式的分类及实现,涵盖创建型、结构型和行为型三大类。内容包含单例、工厂、观察者等常用模式的代码示例与核心逻辑解析,重点阐述了各类模式如何解决特定设计问题。文章最后提供了学习建议,强调结合实际应用场景优先掌握核心模式,并利用现代 C++ 特性优化实现,帮助开发者构建更灵活、可维护的软件系统。

灭霸发布于 2026/3/15更新于 2026/4/251 浏览

C++ 设计模式详解:创建型、结构型与行为型实战

设计模式是解决软件设计中常见问题的成熟方案。在 C++ 开发中,理解并灵活运用这些模式能显著提升代码的可维护性和扩展性。本文将 23 种经典模式分为三大类进行梳理,并结合实际代码示例说明核心实现逻辑。

创建型模式(5 个)

这类模式专注于对象的创建机制,旨在解耦对象的使用者与创建过程。

1. 单例模式 (Singleton)

确保一个类只有一个实例,并提供全局访问点。常用于配置管理器或日志系统。

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;
};

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)

提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。

// 抽象产品 A
class AbstractProductA {
public:
    virtual ~AbstractProductA() {}
    virtual void operationA() = 0;
};

// 抽象产品 B
class AbstractProductB {
public:
    virtual ~AbstractProductB() {}
    virtual void operationB() = 0;
};

// 抽象工厂
class AbstractFactory {
public:
    virtual AbstractProductA* createProductA() = 0;
    virtual AbstractProductB* createProductB() = 0;
};

// 具体工厂 1
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; // 需包含 <vector>
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; // 需包含 <unordered_map>
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; 
    }
};

学习建议

在实际项目中,不必死记硬背所有模式。建议优先掌握以下核心模式:

  1. 单例模式:全局唯一实例,如配置管理器。
  2. 工厂方法模式:对象创建解耦,易于扩展。
  3. 观察者模式:事件处理、消息通知系统。
  4. 策略模式:算法封装,运行时切换。
  5. 装饰器模式:动态添加功能。

次常用的还有适配器、代理、模板方法和命令模式。学习时请多关注应用场景而非单纯背诵代码,避免过度设计。利用 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 智能体了解详情
极客日志微信公众号二维码

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

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

更多推荐文章

查看全部
  • OSCP 实战笔记:获取并破解 Net-NTLMv2 哈希
  • MySQL 行级锁机制详解:Record、Gap 与 Next-Key Lock
  • Dify MCP Server 插件实战:将工作流发布为第三方服务
  • Dify 工作流发布为 MCP Server 实战指南
  • 从 Python 到 OpenClaw:本地 AI 助理构建路径
  • TIOBE 7 月编程语言排行榜发布:Python 稳居榜首,C++ 挑战 C
  • Python 高效清理 Excel 空白行列:原理与实战
  • OpenClaw 多 Agent 路由:Gateway 托管多个 AI 大脑
  • MySQL 解压版安装与配置详解
  • Pyarmor 跨版本兼容指南:Python 2.7 至 3.15 支持方案
  • 设计模式:代理模式详解与实战应用
  • Dubbo 服务降级:Mock 机制原理与实战
  • AI 绘画创意文字全流程:光影、嵌入、隐藏与海报文字实操指南
  • PaperRed:AI 辅助论文写作与查重降重工具解析
  • Seedream 4.0 图像生成模型功能解析与创意玩法
  • VR 虚拟实验室构建:学生与 AI 协同探索科学规律
  • Claude Code Rules 配置实战:规范管理与 Token 优化
  • 大模型核心书籍推荐:从理论到工程实践详解
  • C++ 异常机制详解
  • HDFS DataNode 故障处理:节点下线、数据重建、磁盘更换全流程

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • Gemini 图片去水印

    基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online

  • 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