C++ 设计模式概述
本文介绍了C++中23种设计模式的分类及实现示例,主要分为三大类:
创建型模式(5个):单例模式(常用)、工厂方法模式(常用)、抽象工厂模式(常用)、建造者模式和原型模式。这些模式专注于对象的创建机制。
结构型模式(7个):适配器模式(常用)、桥接模式、组合模式和装饰器模式(常用)等。这些模式处理类和对象的组合方式。
行为型模式:未完整列出,但包含观察者模式等(未展示完整代码)。
文章通过简洁的C++代码示例展示了常用设计模式的实现方法,如单例模式通过私有构造函数和静态方法确保唯一实例,工厂方法模式通过抽象工厂类创建产品等。这些模式为解决特定设计问题提供了可重用的解决方案。
C++ 设计模式概述及常用模式
设计模式可分为三大类:创建型、结构型、行为型。以下是23个设计模式的分类及代码示例:
一、创建型模式(5个)
1. 单例模式(Singleton)⭐ 常用
cpp
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)⭐ 常用
cpp
// 产品接口
class Product {
public:
virtual ~Product() {}
virtual void operation() = 0;
};
// 具体产品
class ConcreteProductA : public Product {
public:
void operation() override {
cout << "Product A operation" << endl;
}
};
// 工厂接口
class Creator {
public:
virtual ~Creator() {}
virtual Product* factoryMethod() = 0;
};
// 具体工厂
class ConcreteCreatorA : public Creator {
public:
Product* factoryMethod() override {
return new ConcreteProductA();
}
};
3. 抽象工厂模式(Abstract Factory)⭐ 常用
cpp
// 抽象产品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)
cpp
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)
cpp
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)⭐ 常用
cpp
// 目标接口
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)
cpp
// 实现接口
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)
cpp
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)⭐ 常用
cpp
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)⭐ 常用
cpp
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)
cpp
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)⭐ 常用
cpp
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)
cpp
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)⭐ 常用
cpp
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)
cpp
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)⭐ 常用
cpp
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)
cpp
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)
cpp
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)⭐ 常用
cpp
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)
cpp
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)⭐ 常用
cpp
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)⭐ 常用
cpp
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)
cpp
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个核心模式:
- 单例模式 - 全局唯一实例,如配置管理器、日志管理器
- 工厂方法模式 - 对象创建解耦,易于扩展
- 观察者模式 - 事件处理、消息通知系统
- 策略模式 - 算法封装,运行时切换
- 装饰器模式 - 动态添加功能
次常用的5个模式:
- 适配器模式 - 接口转换
- 代理模式 - 访问控制、延迟加载
- 模板方法模式 - 算法框架定义
- 命令模式 - 命令封装、撤销/重做
- 外观模式 - 简化复杂子系统接口
学习建议:
- 先从单例、工厂、观察者、策略开始学习
- 理解每种模式的应用场景而不仅仅是代码
- 避免过度设计,只在必要时使用设计模式
- C++11/14/17的现代特性(智能指针、lambda等)可以简化某些模式的实现
这些模式提供了经过验证的解决方案,能帮助你构建更灵活、可维护的软件系统。