跳到主要内容C++ 设计模式详解:分类、实现与核心应用 | 极客日志C++算法
C++ 设计模式详解:分类、实现与核心应用
C++ 设计模式涵盖创建型、结构型与行为型三大类共 23 种模式。文章通过具体代码示例解析了单例、工厂、观察者等常用模式的实现细节,并给出了学习建议与最佳实践。旨在帮助开发者构建灵活可维护的软件系统。
HadoopMan0 浏览 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 { cout << << endl; }
};
{
:
~() {}
= ;
};
: Creator {
:
{ (); }
};
()
override
"Product A operation"
class
Creator
public
virtual
Creator
virtual Product* factoryMethod()
0
class
ConcreteCreatorA
public
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:
string partA;
string partB;
public:
void setPartA(const string& a) { partA = a; }
void setPartB(const 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)
通过复制现有实例来创建新实例,而不是通过 new 关键字。
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 { cout << "Data: " << data << endl; }
};
二、结构型模式(7 个)
6. 适配器模式(Adapter)
class Target {
public:
virtual ~Target() {}
virtual void request() { cout << "Target request" << endl; }
};
class Adaptee {
public:
void specificRequest() { cout << "Adaptee specific request" << 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 { cout << "Leaf operation" << endl; }
};
class Composite : public Component {
private:
vector<Component*> children;
public:
void operation() override {
cout << "Composite operation" << 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 { cout << "ConcreteComponent operation" << 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() { cout << "Added behavior" << endl; }
};
10. 外观模式(Facade)
class SubsystemA {
public:
void operationA() { cout << "Subsystem A operation" << endl; }
};
class SubsystemB {
public:
void operationB() { cout << "Subsystem B operation" << 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 {
cout << "Intrinsic: " << intrinsicState << ", Extrinsic: " << extrinsicState << endl;
}
};
class FlyweightFactory {
private:
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 { cout << "RealSubject request" << 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) {
cout << "Handler1 handled request " << request << endl;
} else if (successor != nullptr) {
successor->handleRequest(request);
}
}
};
14. 命令模式(Command)
class Receiver {
public:
void action() { cout << "Receiver action" << 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:
vector<T> collection;
size_t position;
public:
ConcreteIterator(const 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, 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:
string state;
public:
Memento(const string& s) : state(s) {}
string getState() const { return state; }
};
class Originator {
private:
string state;
public:
void setState(const string& s) { state = s; }
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:
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 {
cout << "Temperature updated: " << temperature << 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 { cout << "Strategy A algorithm" << 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 { cout << "Concrete operation 1" << endl; }
void primitiveOperation2() override { cout << "Concrete operation 2" << 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() { cout << "Operation A" << endl; }
};
四、学习建议
在实际开发中,不必掌握所有模式,建议优先关注以下核心内容:
- 单例模式 - 全局唯一实例,如配置管理器、日志管理器
- 工厂方法模式 - 对象创建解耦,易于扩展
- 观察者模式 - 事件处理、消息通知系统
- 策略模式 - 算法封装,运行时切换
- 装饰器模式 - 动态添加功能
次常用的 5 个模式:
6. 适配器模式 - 接口转换
7. 代理模式 - 访问控制、延迟加载
8. 模板方法模式 - 算法框架定义
9. 命令模式 - 命令封装、撤销/重做
10. 外观模式 - 简化复杂子系统接口
- 先从单例、工厂、观察者、策略开始学习
- 理解每种模式的应用场景而不仅仅是代码
- 避免过度设计,只在必要时使用设计模式
- C++11/14/17 的现代特性(智能指针、lambda 等)可以简化某些模式的实现
这些模式提供了经过验证的解决方案,能帮助你构建更灵活、可维护的软件系统。
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,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
- JSON 压缩
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online