目录
- 第一部分:设计原则
- 第一章:SOLID 原则
- 第二章:其他重要原则
- 第二部分:创建型模式
- 第三章:单例模式(Singleton)
- 第四章:工厂方法模式(Factory Method)
- 第五章:抽象工厂模式(Abstract Factory)
- 第六章:建造者模式(Builder)
- 第七章:原型模式(Prototype)
- 第三部分:结构型模式
- 第八章:适配器模式(Adapter)
- 第九章:桥接模式(Bridge)
- 第十章:组合模式(Composite)
- 第十一章:装饰器模式(Decorator)
- 第十二章:外观模式(Facade)
- 第十三章:享元模式(Flyweight)
- 第十四章:代理模式(Proxy)
- 第四部分:行为型模式
- 第十五章:责任链模式(Chain of Responsibility)
- 第十六章:命令模式(Command)
- 第十七章:迭代器模式(Iterator)
- 第十八章:中介者模式(Mediator)
- 第十九章:备忘录模式(Memento)
- 第二十章:观察者模式(Observer)
- 第二十一章:状态模式(State)
- 第二十二章:策略模式(Strategy)
- 第二十三章:模板方法模式(Template Method)
- 第二十四章:访问者模式(Visitor)
第一部分:设计原则
第一章:SOLID 原则
1.1 S --- 单一职责原则(SRP)
定义:一个类应该只有一个引起它变化的原因。
违反 SRP 的例子:
cpp
// 错误:一个类承担了多个职责
class Employee {
public:
void calculatePay() { /* 计算工资 */ }
void saveToDatabase() { /* 保存到数据库 */ }
void generateReport() { /* 生成报告 */ }
};
遵循 SRP 的例子:
cpp
// 正确:每个类只有一个职责
class Employee {
std::string name_;
double salary_;
public:
const std::string& getName() const { return name_; }
double getSalary() const { return salary_; }
};
class PayCalculator {
public:
double calculate(const Employee& emp) {
return emp.getSalary() * 1.1; // 加上奖金
}
};
class EmployeeRepository {
public:
void save(const Employee& emp) { /* 保存到数据库 */ }
};
class ReportGenerator {
public:
std::string generate(const Employee& emp) { /* 生成报告 */ }
};
好处:
- 每个类职责单一,易于理解和维护
- 修改一个职责不会影响其他职责
- 更容易进行单元测试
1.2 O --- 开闭原则(OCP)
定义:软件实体应该对扩展开放,对修改关闭。
违反 OCP 的例子:
cpp
// 错误:添加新形状需要修改 AreaCalculator
class AreaCalculator {
public:
double calculate(const Shape& shape) {
if (shape.type == ShapeType::CIRCLE) {
return 3.14 * shape.radius * shape.radius;
} else if (shape.type == ShapeType::RECTANGLE) {
return shape.width * shape.height;
}
// 添加新形状需要修改这里!
return 0;
}
};
遵循 OCP 的例子:
cpp
// 正确:通过多态扩展,无需修改已有代码
class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() = default;
};
class Circle : public Shape {
double radius_;
public:
Circle(double r) : radius_(r) {}
double area() const override { return 3.14159 * radius_ * radius_; }
};
class Rectangle : public Shape {
double width_, height_;
public:
Rectangle(double w, double h) : width_(w), height_(h) {}
double area() const override { return width_ * height_; }
};
// 添加新形状无需修改 AreaCalculator
class Triangle : public Shape {
double base_, height_;
public:
Triangle(double b, double h) : base_(b), height_(h) {}
double area() const override { return 0.5 * base_ * height_; }
};
class AreaCalculator {
public:
double calculate(const Shape& shape) {
return shape.area(); // 多态调用
}
};
1.3 L --- 里氏替换原则(LSP)
定义:子类必须能够替换它的父类。
违反 LSP 的例子:
cpp
// 错误:Square 不能正确替换 Rectangle
class Rectangle {
protected:
double width_, height_;
public:
virtual void setWidth(double w) { width_ = w; }
virtual void setHeight(double h) { height_ = h; }
double area() const { return width_ * height_; }
};
class Square : public Rectangle {
public:
void setWidth(double w) override { width_ = height_ = w; }
void setHeight(double h) override { width_ = height_ = h; }
};
// 问题:这个函数对 Square 不正确
void process(Rectangle& r) {
r.setWidth(5);
r.setHeight(4);
assert(r.area() == 20); // 对 Square 会失败!
}
遵循 LSP 的例子:
cpp
// 正确:使用不可变对象
class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() = default;
};
class Rectangle : public Shape {
double width_, height_;
public:
Rectangle(double w, double h) : width_(w), height_(h) {}
double area() const override { return width_ * height_; }
};
class Square : public Shape {
double side_;
public:
Square(double s) : side_(s) {}
double area() const override { return side_ * side_; }
};
1.4 I --- 接口隔离原则(ISP)
定义:客户端不应该被迫依赖于它们不使用的接口。
违反 ISP 的例子:
cpp
// 错误:一个臃肿的接口
class IWorker {
public:
virtual void work() = 0;
virtual void eat() = 0;
virtual void sleep() = 0;
virtual ~IWorker() = default;
};
// Robot 不需要 eat 和 sleep
class Robot : public IWorker {
public:
void work() override { /* 工作 */ }
void eat() override { /* 机器人不需要吃饭! */ }
void sleep() override { /* 机器人不需要睡觉! */ }
};
遵循 ISP 的例子:
cpp
// 正确:分离接口
class IWorkable {
public:
virtual void work() = 0;
virtual ~IWorkable() = default;
};
class IFeedable {
public:
virtual void eat() = 0;
virtual ~IFeedable() = default;
};
class ISleepable {
public:
virtual void sleep() = 0;
virtual ~ISleepable() = default;
};
// 人类实现所有接口
class Human : public IWorkable, public IFeedable, public ISleepable {
public:
void work() override { /* 工作 */ }
void eat() override { /* 吃饭 */ }
void sleep() override { /* 睡觉 */ }
};
// 机器人只实现工作接口
class Robot : public IWorkable {
public:
void work() override { /* 工作 */ }
};
1.5 D --- 依赖倒置原则(DIP)
定义:
- 高层模块不应该依赖于低层模块,二者都应该依赖于抽象。
- 抽象不应该依赖于细节,细节应该依赖于抽象。
违反 DIP 的例子:
cpp
// 错误:高层模块直接依赖低层模块
class MySQLDatabase {
public:
void save(const std::string& data) { /* MySQL 保存 */ }
};
class UserService {
MySQLDatabase db_; // 直接依赖具体类
public:
void saveUser(const std::string& user) {
db_.save(user);
}
};
遵循 DIP 的例子:
cpp
// 正确:依赖于抽象
class IDatabase {
public:
virtual void save(const std::string& data) = 0;
virtual ~IDatabase() = default;
};
class MySQLDatabase : public IDatabase {
public:
void save(const std::string& data) override { /* MySQL 保存 */ }
};
class PostgreSQLDatabase : public IDatabase {
public:
void save(const std::string& data) override { /* PostgreSQL 保存 */ }
};
class UserService {
std::unique_ptr<IDatabase> db_; // 依赖抽象
public:
UserService(std::unique_ptr<IDatabase> db) : db_(std::move(db)) {}
void saveUser(const std::string& user) {
db_->save(user);
}
};
// 使用
auto db = std::make_unique<MySQLDatabase>();
UserService service(std::move(db));
第二章:其他重要原则
2.1 迪米特法则(最少知识原则)
定义:一个对象应该对其他对象有最少的了解。
cpp
// 违反:链式调用
customer.getOrder().getItems().getFirst().getName();
// 遵循:提供快捷方法
customer.getFirstItemName();
2.2 合成复用原则
定义:优先使用组合/聚合,而不是继承。
cpp
// 继承(不推荐)
class Stack : public std::vector<int> { /* ... */ };
// 组合(推荐)
class Stack {
std::vector<int> data_; // 组合
public:
void push(int value) { data_.push_back(value); }
void pop() { data_.pop_back(); }
int top() const { return data_.back(); }
};
第二部分:创建型模式
第三章:单例模式(Singleton)
3.1 意图
保证一个类只有一个实例,并提供一个全局访问点。
3.2 结构
┌─────────────┐
│ Singleton │
├─────────────┤
│ - instance │
├─────────────┤
│ + getInstance() │
│ + operation() │
└─────────────┘
3.3 实现
3.3.1 懒汉式(线程不安全)
cpp
class Singleton {
private:
static Singleton* instance_;
Singleton() {} // 私有构造函数
public:
static Singleton* getInstance() {
if (instance_ == nullptr) {
instance_ = new Singleton();
}
return instance_;
}
void operation() {
std::cout << "Singleton operation" << std::endl;
}
};
Singleton* Singleton::instance_ = nullptr;
3.3.2 懒汉式(线程安全)
cpp
#include <mutex>
class Singleton {
private:
static Singleton* instance_;
static std::mutex mutex_;
Singleton() {}
public:
static Singleton* getInstance() {
std::lock_guard<std::mutex> lock(mutex_);
if (instance_ == nullptr) {
instance_ = new Singleton();
}
return instance_;
}
};
Singleton* Singleton::instance_ = nullptr;
std::mutex Singleton::mutex_;
3.3.3 双重检查锁定(DCLP)
cpp
class Singleton {
private:
static std::atomic<Singleton*> instance_;
static std::mutex mutex_;
Singleton() {}
public:
static Singleton* getInstance() {
Singleton* tmp = instance_.load(std::memory_order_acquire);
if (tmp == nullptr) {
std::lock_guard<std::mutex> lock(mutex_);
tmp = instance_.load(std::memory_order_relaxed);
if (tmp == nullptr) {
tmp = new Singleton();
instance_.store(tmp, std::memory_order_release);
}
}
return tmp;
}
};
std::atomic<Singleton*> Singleton::instance_{nullptr};
std::mutex Singleton::mutex_;
3.3.4 Meyers 单例(C++11 推荐)
cpp
class Singleton {
private:
Singleton() {}
~Singleton() {}
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton& getInstance() {
static Singleton instance; // C++11 保证线程安全
return instance;
}
void operation() {
std::cout << "Singleton operation" << std::endl;
}
};
// 使用
Singleton::getInstance().operation();
3.4 优缺点
| 优点 | 缺点 |
|---|---|
| 全局访问点 | 违反单一职责原则 |
| 节省内存 | 难以单元测试 |
| 线程安全(Meyers) | 隐藏依赖关系 |
第四章:工厂方法模式(Factory Method)
4.1 意图
定义一个创建对象的接口,让子类决定实例化哪一个类。
4.2 结构
┌──────────────┐ ┌──────────────┐
│ Creator │ │ Product │
├──────────────┤ ├──────────────┤
│ │ │ │
├──────────────┤ ├──────────────┤
│ + create() │────────→│ + operation()│
└──────┬───────┘ └──────┬───────┘
│ │
┌──────┴───────┐ ┌──────┴───────┐
│ConcreteCreator│ │ConcreteProduct│
├──────────────┤ ├──────────────┤
│ + create() │────────→│ + operation()│
└──────────────┘ └──────────────┘
4.3 实现
cpp
// 产品接口
class Product {
public:
virtual std::string operation() const = 0;
virtual ~Product() = default;
};
// 具体产品
class ConcreteProductA : public Product {
public:
std::string operation() const override {
return "Product A";
}
};
class ConcreteProductB : public Product {
public:
std::string operation() const override {
return "Product B";
}
};
// 创建者
class Creator {
public:
virtual std::unique_ptr<Product> create() const = 0;
virtual ~Creator() = default;
// 模板方法:使用工厂方法
std::string someOperation() const {
auto product = create();
return "Creator: " + product->operation();
}
};
// 具体创建者
class ConcreteCreatorA : public Creator {
public:
std::unique_ptr<Product> create() const override {
return std::make_unique<ConcreteProductA>();
}
};
class ConcreteCreatorB : public Creator {
public:
std::unique_ptr<Product> create() const override {
return std::make_unique<ConcreteProductB>();
}
};
// 使用
void clientCode(const Creator& creator) {
std::cout << creator.someOperation() << std::endl;
}
int main() {
ConcreteCreatorA creatorA;
clientCode(creatorA); // "Creator: Product A"
ConcreteCreatorB creatorB;
clientCode(creatorB); // "Creator: Product B"
}
4.4 优缺点
| 优点 | 缺点 |
|---|---|
| 遵循开闭原则 | 类数量增加 |
| 避免紧密耦合 | 代码复杂度增加 |
| 单一职责 | --- |
第五章:抽象工厂模式(Abstract Factory)
5.1 意图
提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
5.2 结构
┌─────────────────────┐
│ AbstractFactory │
├─────────────────────┤
│ + createProductA() │
│ + createProductB() │
└──────────┬──────────┘
│
┌──────┴──────┐
│ │
┌───┴────┐ ┌───┴────┐
│Factory1│ │Factory2│
├────────┤ ├────────┤
│+createA│ │+createA│
│+createB│ │+createB│
└────────┘ └────────┘
5.3 实现
cpp
// 抽象产品
class Button {
public:
virtual void paint() const = 0;
virtual ~Button() = default;
};
class Checkbox {
public:
virtual void paint() const = 0;
virtual ~Checkbox() = default;
};
// 具体产品 - Windows 风格
class WindowsButton : public Button {
public:
void paint() const override {
std::cout << "Windows Button" << std::endl;
}
};
class WindowsCheckbox : public Checkbox {
public:
void paint() const override {
std::cout << "Windows Checkbox" << std::endl;
}
};
// 具体产品 - Mac 风格
class MacButton : public Button {
public:
void paint() const override {
std::cout << "Mac Button" << std::endl;
}
};
class MacCheckbox : public Checkbox {
public:
void paint() const override {
std::cout << "Mac Checkbox" << std::endl;
}
};
// 抽象工厂
class GUIFactory {
public:
virtual std::unique_ptr<Button> createButton() const = 0;
virtual std::unique_ptr<Checkbox> createCheckbox() const = 0;
virtual ~GUIFactory() = default;
};
// 具体工厂
class WindowsFactory : public GUIFactory {
public:
std::unique_ptr<Button> createButton() const override {
return std::make_unique<WindowsButton>();
}
std::unique_ptr<Checkbox> createCheckbox() const override {
return std::make_unique<WindowsCheckbox>();
}
};
class MacFactory : public GUIFactory {
public:
std::unique_ptr<Button> createButton() const override {
return std::make_unique<MacButton>();
}
std::unique_ptr<Checkbox> createCheckbox() const override {
return std::make_unique<MacCheckbox>();
}
};
// 客户端代码
class Application {
std::unique_ptr<Button> button_;
std::unique_ptr<Checkbox> checkbox_;
public:
Application(const GUIFactory& factory) {
button_ = factory.createButton();
checkbox_ = factory.createCheckbox();
}
void paint() {
button_->paint();
checkbox_->paint();
}
};
第六章:建造者模式(Builder)
6.1 意图
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
6.2 实现
cpp
// 产品
class House {
std::string walls_;
std::string roof_;
std::string door_;
std::string windows_;
std::string garden_;
public:
void setWalls(const std::string& w) { walls_ = w; }
void setRoof(const std::string& r) { roof_ = r; }
void setDoor(const std::string& d) { door_ = d; }
void setWindows(const std::string& w) { windows_ = w; }
void setGarden(const std::string& g) { garden_ = g; }
std::string toString() const {
return "House[walls=" + walls_ + ", roof=" + roof_ +
", door=" + door_ + ", windows=" + windows_ +
", garden=" + garden_ + "]";
}
};
// 抽象建造者
class HouseBuilder {
protected:
std::unique_ptr<House> house_;
public:
HouseBuilder() : house_(std::make_unique<House>()) {}
virtual ~HouseBuilder() = default;
virtual void buildWalls() = 0;
virtual void buildRoof() = 0;
virtual void buildDoor() = 0;
virtual void buildWindows() = 0;
virtual void buildGarden() = 0;
std::unique_ptr<House> getResult() {
return std::move(house_);
}
};
// 具体建造者 - 豪华别墅
class LuxuryHouseBuilder : public HouseBuilder {
public:
void buildWalls() override { house_->setWalls("大理石墙壁"); }
void buildRoof() override { house_->setRoof("琉璃瓦屋顶"); }
void buildDoor() override { house_->setDoor("实木大门"); }
void buildWindows() override { house_->setWindows("落地窗"); }
void buildGarden() override { house_->setGarden("私家花园"); }
};
// 具体建造者 - 普通住宅
class SimpleHouseBuilder : public HouseBuilder {
public:
void buildWalls() override { house_->setWalls("砖墙"); }
void buildRoof() override { house_->setRoof("水泥屋顶"); }
void buildDoor() override { house_->setDoor("铁门"); }
void buildWindows() override { house_->setWindows("普通窗户"); }
void buildGarden() override { house_->setGarden("无花园"); }
};
// 指挥者
class Director {
public:
std::unique_ptr<House> construct(HouseBuilder& builder) {
builder.buildWalls();
builder.buildRoof();
builder.buildDoor();
builder.buildWindows();
builder.buildGarden();
return builder.getResult();
}
};
// 使用
Director director;
LuxuryHouseBuilder luxuryBuilder;
auto luxuryHouse = director.construct(luxuryBuilder);
std::cout << luxuryHouse->toString() << std::endl;
SimpleHouseBuilder simpleBuilder;
auto simpleHouse = director.construct(simpleBuilder);
std::cout << simpleHouse->toString() << std::endl;
6.3 优缺点
| 优点 | 缺点 |
|---|---|
| 分步构建复杂对象 | 代码复杂度增加 |
| 复用构建逻辑 | --- |
| 单一职责 | --- |
第七章:原型模式(Prototype)
7.1 意图
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
7.2 实现
cpp
// 原型接口
class Prototype {
public:
virtual std::unique_ptr<Prototype> clone() const = 0;
virtual std::string toString() const = 0;
virtual ~Prototype() = default;
};
// 具体原型
class ConcretePrototype : public Prototype {
std::string name_;
int value_;
std::vector<int> data_;
public:
ConcretePrototype(const std::string& name, int value, const std::vector<int>& data)
: name_(name), value_(value), data_(data) {}
std::unique_ptr<Prototype> clone() const override {
return std::make_unique<ConcretePrototype>(*this); // 拷贝构造
}
std::string toString() const override {
return "Prototype[name=" + name_ + ", value=" + std::to_string(value_) + "]";
}
void setValue(int v) { value_ = v; }
};
// 原型管理器
class PrototypeManager {
std::unordered_map<std::string, std::unique_ptr<Prototype>> prototypes_;
public:
void registerPrototype(const std::string& name, std::unique_ptr<Prototype> proto) {
prototypes_[name] = std::move(proto);
}
std::unique_ptr<Prototype> create(const std::string& name) {
auto it = prototypes_.find(name);
if (it != prototypes_.end()) {
return it->second->clone();
}
return nullptr;
}
};
// 使用
PrototypeManager manager;
manager.registerPrototype("proto1",
std::make_unique<ConcretePrototype>("Test", 42, std::vector<int>{1, 2, 3}));
auto clone = manager.create("proto1");
std::cout << clone->toString() << std::endl; // "Prototype[name=Test, value=42]"
第三部分:结构型模式
第八章:适配器模式(Adapter)
8.1 意图
将一个类的接口转换成客户希望的另一个接口。
8.2 实现
cpp
// 目标接口
class Target {
public:
virtual std::string request() const = 0;
virtual ~Target() = default;
};
// 被适配者(已有类)
class Adaptee {
public:
std::string specificRequest() const {
return "Adaptee: 特殊请求";
}
};
// 适配器(对象适配器)
class Adapter : public Target {
std::unique_ptr<Adaptee> adaptee_;
public:
Adapter(std::unique_ptr<Adaptee> adaptee) : adaptee_(std::move(adaptee)) {}
std::string request() const override {
return "Adapter: " + adaptee_->specificRequest();
}
};
// 使用
auto adaptee = std::make_unique<Adaptee>();
Adapter adapter(std::move(adaptee));
std::cout << adapter.request() << std::endl;
// 输出: "Adapter: Adaptee: 特殊请求"
8.3 类适配器(多重继承)
cpp
class Adapter : public Target, private Adaptee {
public:
std::string request() const override {
return "Adapter: " + specificRequest();
}
};
第九章:桥接模式(Bridge)
9.1 意图
将抽象部分与实现部分分离,使它们都可以独立变化。
9.2 实现
cpp
// 实现接口
class Implementation {
public:
virtual std::string operationImpl() const = 0;
virtual ~Implementation() = default;
};
// 具体实现
class ConcreteImplementationA : public Implementation {
public:
std::string operationImpl() const override {
return "Implementation A";
}
};
class ConcreteImplementationB : public Implementation {
public:
std::string operationImpl() const override {
return "Implementation B";
}
};
// 抽象
class Abstraction {
protected:
std::shared_ptr<Implementation> impl_;
public:
Abstraction(std::shared_ptr<Implementation> impl) : impl_(impl) {}
virtual ~Abstraction() = default;
virtual std::string operation() const {
return "Abstraction: " + impl_->operationImpl();
}
};
// 扩展抽象
class ExtendedAbstraction : public Abstraction {
public:
ExtendedAbstraction(std::shared_ptr<Implementation> impl) : Abstraction(impl) {}
std::string operation() const override {
return "ExtendedAbstraction: " + impl_->operationImpl();
}
};
// 使用
auto implA = std::make_shared<ConcreteImplementationA>();
Abstraction abs1(implA);
std::cout << abs1.operation() << std::endl;
auto implB = std::make_shared<ConcreteImplementationB>();
ExtendedAbstraction abs2(implB);
std::cout << abs2.operation() << std::endl;
第十章:组合模式(Composite)
10.1 意图
将对象组合成树形结构以表示"部分-整体"的层次结构。
10.2 实现
cpp
// 组件接口
class Component {
protected:
std::string name_;
public:
Component(const std::string& name) : name_(name) {}
virtual ~Component() = default;
virtual void add(std::shared_ptr<Component> component) {}
virtual void remove(std::shared_ptr<Component> component) {}
virtual bool isComposite() const { return false; }
virtual std::string operation() const = 0;
};
// 叶子节点
class Leaf : public Component {
public:
Leaf(const std::string& name) : Component(name) {}
std::string operation() const override {
return "Leaf[" + name_ + "]";
}
};
// 组合节点
class Composite : public Component {
std::vector<std::shared_ptr<Component>> children_;
public:
Composite(const std::string& name) : Component(name) {}
void add(std::shared_ptr<Component> component) override {
children_.push_back(component);
}
void remove(std::shared_ptr<Component> component) override {
children_.erase(
std::remove(children_.begin(), children_.end(), component),
children_.end()
);
}
bool isComposite() const override { return true; }
std::string operation() const override {
std::string result = "Branch[" + name_ + "](";
for (size_t i = 0; i < children_.size(); ++i) {
if (i > 0) result += "+";
result += children_[i]->operation();
}
result += ")";
return result;
}
};
// 使用
auto tree = std::make_shared<Composite>("root");
auto branch1 = std::make_shared<Composite>("branch1");
auto branch2 = std::make_shared<Composite>("branch2");
branch1->add(std::make_shared<Leaf>("leaf1"));
branch1->add(std::make_shared<Leaf>("leaf2"));
branch2->add(std::make_shared<Leaf>("leaf3"));
tree->add(branch1);
tree->add(branch2);
std::cout << tree->operation() << std::endl;
// "Branch[root](Branch[branch1](Leaf[leaf1]+Leaf[leaf2])+Branch[branch2](Leaf[leaf3]))"
第十一章:装饰器模式(Decorator)
11.1 意图
动态地给一个对象添加一些额外的职责。
11.2 实现
cpp
// 组件接口
class Component {
public:
virtual std::string operation() const = 0;
virtual ~Component() = default;
};
// 具体组件
class ConcreteComponent : public Component {
public:
std::string operation() const override {
return "ConcreteComponent";
}
};
// 装饰器基类
class Decorator : public Component {
protected:
std::shared_ptr<Component> component_;
public:
Decorator(std::shared_ptr<Component> comp) : component_(comp) {}
std::string operation() const override {
return component_->operation();
}
};
// 具体装饰器 A
class ConcreteDecoratorA : public Decorator {
public:
ConcreteDecoratorA(std::shared_ptr<Component> comp) : Decorator(comp) {}
std::string operation() const override {
return "DecoratorA(" + Decorator::operation() + ")";
}
};
// 具体装饰器 B
class ConcreteDecoratorB : public Decorator {
public:
ConcreteDecoratorB(std::shared_ptr<Component> comp) : Decorator(comp) {}
std::string operation() const override {
return "DecoratorB(" + Decorator::operation() + ")";
}
};
// 使用
auto simple = std::make_shared<ConcreteComponent>();
auto decoratorA = std::make_shared<ConcreteDecoratorA>(simple);
auto decoratorB = std::make_shared<ConcreteDecoratorB>(decoratorA);
std::cout << decoratorB->operation() << std::endl;
// "DecoratorB(DecoratorA(ConcreteComponent))"
第十二章:外观模式(Facade)
12.1 意图
为子系统中的一组接口提供一个一致的界面。
12.2 实现
cpp
// 子系统类
class CPU {
public:
void freeze() { std::cout << "CPU: 冻结" << std::endl; }
void execute() { std::cout << "CPU: 执行" << std::endl; }
};
class Memory {
public:
void load(long position, const std::string& data) {
std::cout << "Memory: 加载数据到位置 " << position << std::endl;
}
};
class HardDrive {
public:
std::string read(long sector, int size) {
std::cout << "HardDrive: 读取扇区 " << sector << std::endl;
return "data";
}
};
// 外观
class ComputerFacade {
CPU cpu_;
Memory memory_;
HardDrive hardDrive_;
public:
void start() {
std::cout << "=== 计算机启动 ===" << std::endl;
cpu_.freeze();
std::string bootData = hardDrive_.read(0, 1024);
memory_.load(0, bootData);
cpu_.execute();
std::cout << "=== 计算机启动完成 ===" << std::endl;
}
};
// 使用
ComputerFacade computer;
computer.start();
第十三章:享元模式(Flyweight)
13.1 意图
运用共享技术有效地支持大量细粒度的对象。
13.2 实现
cpp
// 享元
class Flyweight {
protected:
std::string intrinsicState_; // 内部状态(共享)
public:
Flyweight(const std::string& state) : intrinsicState_(state) {}
void operation(const std::string& extrinsicState) const {
std::cout << "Flyweight[" << intrinsicState_ << "] with " << extrinsicState << std::endl;
}
};
// 享元工厂
class FlyweightFactory {
std::unordered_map<std::string, std::shared_ptr<Flyweight>> flyweights_;
std::string getKey(const std::string& state) const {
return state; // 简化:直接使用状态作为键
}
public:
std::shared_ptr<Flyweight> getFlyweight(const std::string& sharedState) {
std::string key = getKey(sharedState);
if (flyweights_.find(key) == flyweights_.end()) {
std::cout << "创建新享元: " << sharedState << std::endl;
flyweights_[key] = std::make_shared<Flyweight>(sharedState);
} else {
std::cout << "复用已有享元: " << sharedState << std::endl;
}
return flyweights_[key];
}
size_t getCount() const { return flyweights_.size(); }
};
// 使用
FlyweightFactory factory;
auto f1 = factory.getFlyweight("shared1");
auto f2 = factory.getFlyweight("shared1"); // 复用
auto f3 = factory.getFlyweight("shared2"); // 新建
f1->operation("unique1");
f2->operation("unique2");
std::cout << "享元数量: " << factory.getCount() << std::endl; // 2
第十四章:代理模式(Proxy)
14.1 意图
为其他对象提供一种代理以控制对这个对象的访问。
14.2 实现
cpp
// 接口
class Subject {
public:
virtual void request() const = 0;
virtual ~Subject() = default;
};
// 真实主题
class RealSubject : public Subject {
public:
void request() const override {
std::cout << "RealSubject: 处理请求" << std::endl;
}
};
// 代理
class Proxy : public Subject {
std::unique_ptr<RealSubject> realSubject_;
bool checkAccess() const {
std::cout << "Proxy: 检查访问权限" << std::endl;
return true;
}
void logAccess() const {
std::cout << "Proxy: 记录日志" << std::endl;
}
public:
void request() const override {
if (checkAccess()) {
if (!realSubject_) {
realSubject_ = std::make_unique<RealSubject>();
}
realSubject_->request();
logAccess();
}
}
};
// 使用
Proxy proxy;
proxy.request();
// 输出:
// Proxy: 检查访问权限
// RealSubject: 处理请求
// Proxy: 记录日志
第四部分:行为型模式
第十五章:责任链模式(Chain of Responsibility)
15.1 意图
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合。
15.2 实现
cpp
// 处理者接口
class Handler {
public:
virtual std::shared_ptr<Handler> setNext(std::shared_ptr<Handler> handler) = 0;
virtual std::string handle(const std::string& request) = 0;
virtual ~Handler() = default;
};
// 抽象处理者
class AbstractHandler : public Handler {
protected:
std::shared_ptr<Handler> nextHandler_;
public:
std::shared_ptr<Handler> setNext(std::shared_ptr<Handler> handler) override {
nextHandler_ = handler;
return handler;
}
std::string handle(const std::string& request) override {
if (nextHandler_) {
return nextHandler_->handle(request);
}
return "";
}
};
// 具体处理者
class AuthHandler : public AbstractHandler {
public:
std::string handle(const std::string& request) override {
if (request.find("auth") != std::string::npos) {
return "AuthHandler: 已认证";
}
return AbstractHandler::handle(request);
}
};
class LogHandler : public AbstractHandler {
public:
std::string handle(const std::string& request) override {
if (request.find("log") != std::string::npos) {
return "LogHandler: 已记录日志";
}
return AbstractHandler::handle(request);
}
};
class ErrorHandler : public AbstractHandler {
public:
std::string handle(const std::string& request) override {
if (request.find("error") != std::string::npos) {
return "ErrorHandler: 已处理错误";
}
return AbstractHandler::handle(request);
}
};
// 使用
auto auth = std::make_shared<AuthHandler>();
auto log = std::make_shared<LogHandler>();
auto error = std::make_shared<ErrorHandler>();
auth->setNext(log)->setNext(error);
std::cout << auth->handle("auth request") << std::endl; // "AuthHandler: 已认证"
std::cout << auth->handle("log request") << std::endl; // "LogHandler: 已记录日志"
std::cout << auth->handle("error request") << std::endl; // "ErrorHandler: 已处理错误"
第十六章:命令模式(Command)
16.1 意图
将一个请求封装为一个对象,从而可以用不同的请求对客户进行参数化。
16.2 实现
cpp
// 命令接口
class Command {
public:
virtual void execute() = 0;
virtual void undo() = 0;
virtual ~Command() = default;
};
// 接收者
class Light {
bool isOn_ = false;
public:
void turnOn() { isOn_ = true; std::cout << "灯已打开" << std::endl; }
void turnOff() { isOn_ = false; std::cout << "灯已关闭" << std::endl; }
bool isOn() const { return isOn_; }
};
// 具体命令
class LightOnCommand : public Command {
Light& light_;
public:
LightOnCommand(Light& light) : light_(light) {}
void execute() override { light_.turnOn(); }
void undo() override { light_.turnOff(); }
};
class LightOffCommand : public Command {
Light& light_;
public:
LightOffCommand(Light& light) : light_(light) {}
void execute() override { light_.turnOff(); }
void undo() override { light_.turnOn(); }
};
// 调用者
class RemoteControl {
std::vector<std::shared_ptr<Command>> history_;
public:
void pressButton(std::shared_ptr<Command> command) {
command->execute();
history_.push_back(command);
}
void pressUndo() {
if (!history_.empty()) {
history_.back()->undo();
history_.pop_back();
}
}
};
// 使用
Light light;
auto onCmd = std::make_shared<LightOnCommand>(light);
auto offCmd = std::make_shared<LightOffCommand>(light);
RemoteControl remote;
remote.pressButton(onCmd); // "灯已打开"
remote.pressButton(offCmd); // "灯已关闭"
remote.pressUndo(); // "灯已打开"
第十七章:迭代器模式(Iterator)
17.1 意图
提供一种方法顺序访问一个聚合对象中各个元素,而不暴露该对象的内部表示。
17.2 实现
cpp
// 迭代器接口
template <typename T>
class Iterator {
public:
virtual bool hasNext() const = 0;
virtual T next() = 0;
virtual ~Iterator() = default;
};
// 集合接口
template <typename T>
class Iterable {
public:
virtual std::unique_ptr<Iterator<T>> createIterator() = 0;
virtual ~Iterable() = default;
};
// 具体集合
template <typename T>
class ConcreteCollection : public Iterable<T> {
std::vector<T> items_;
public:
void add(const T& item) { items_.push_back(item); }
size_t size() const { return items_.size(); }
T get(size_t index) const { return items_[index]; }
std::unique_ptr<Iterator<T>> createIterator() override;
};
// 具体迭代器
template <typename T>
class ConcreteIterator : public Iterator<T> {
const ConcreteCollection<T>& collection_;
size_t position_ = 0;
public:
ConcreteIterator(const ConcreteCollection<T>& collection)
: collection_(collection) {}
bool hasNext() const override {
return position_ < collection_.size();
}
T next() override {
return collection_.get(position_++);
}
};
template <typename T>
std::unique_ptr<Iterator<T>> ConcreteCollection<T>::createIterator() {
return std::make_unique<ConcreteIterator<T>>(*this);
}
// 使用
ConcreteCollection<int> collection;
collection.add(1);
collection.add(2);
collection.add(3);
auto it = collection.createIterator();
while (it->hasNext()) {
std::cout << it->next() << " ";
}
// 输出: 1 2 3
第十八章:中介者模式(Mediator)
18.1 意图
用一个中介对象来封装一系列的对象交互。
18.2 实现
cpp
// 中介者接口
class Colleague;
class Mediator {
public:
virtual void notify(Colleague* sender, const std::string& event) = 0;
virtual ~Mediator() = default;
};
// 同事类
class Colleague {
protected:
Mediator* mediator_;
public:
Colleague(Mediator* mediator = nullptr) : mediator_(mediator) {}
void setMediator(Mediator* mediator) { mediator_ = mediator; }
};
// 具体同事
class Button : public Colleague {
public:
void click() {
std::cout << "按钮被点击" << std::endl;
if (mediator_) mediator_->notify(this, "click");
}
};
class TextBox : public Colleague {
std::string text_;
public:
void setText(const std::string& text) {
text_ = text;
std::cout << "文本框内容: " << text_ << std::endl;
if (mediator_) mediator_->notify(this, "textChanged");
}
const std::string& getText() const { return text_; }
};
class Label : public Colleague {
public:
void setText(const std::string& text) {
std::cout << "标签内容: " << text << std::endl;
}
};
// 具体中介者
class DialogMediator : public Mediator {
Button* button_;
TextBox* textBox_;
Label* label_;
public:
DialogMediator(Button* btn, TextBox* txt, Label* lbl)
: button_(btn), textBox_(txt), label_(lbl) {
button_->setMediator(this);
textBox_->setMediator(this);
label_->setMediator(this);
}
void notify(Colleague* sender, const std::string& event) override {
if (sender == button_ && event == "click") {
label_->setText("按钮已被点击: " + textBox_->getText());
} else if (sender == textBox_ && event == "textChanged") {
label_->setText("当前文本: " + textBox_->getText());
}
}
};
// 使用
Button button;
TextBox textBox;
Label label;
DialogMediator mediator(&button, &textBox, &label);
textBox.setText("Hello");
button.click();
第十九章:备忘录模式(Memento)
19.1 意图
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
19.2 实现
cpp
// 备忘录
class Memento {
std::string state_;
public:
Memento(const std::string& state) : state_(state) {}
std::string getState() const { return state_; }
};
// 发起人
class Originator {
std::string state_;
public:
void setState(const std::string& state) {
state_ = state;
std::cout << "状态设置为: " << state_ << std::endl;
}
std::string getState() const { return state_; }
std::unique_ptr<Memento> save() const {
return std::make_unique<Memento>(state_);
}
void restore(const Memento& memento) {
state_ = memento.getState();
std::cout << "状态恢复为: " << state_ << std::endl;
}
};
// 管理者
class Caretaker {
std::vector<std::unique_ptr<Memento>> history_;
public:
void save(const Originator& originator) {
history_.push_back(originator.save());
}
void undo(Originator& originator) {
if (!history_.empty()) {
originator.restore(*history_.back());
history_.pop_back();
}
}
};
// 使用
Originator originator;
Caretaker caretaker;
originator.setState("状态1");
caretaker.save(originator);
originator.setState("状态2");
caretaker.save(originator);
originator.setState("状态3");
caretaker.undo(originator); // "状态恢复为: 状态2"
caretaker.undo(originator); // "状态恢复为: 状态1"
第二十章:观察者模式(Observer)
20.1 意图
定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
20.2 实现
cpp
// 观察者接口
class Observer {
public:
virtual void update(const std::string& message) = 0;
virtual ~Observer() = default;
};
// 主题接口
class Subject {
public:
virtual void attach(std::shared_ptr<Observer> observer) = 0;
virtual void detach(std::shared_ptr<Observer> observer) = 0;
virtual void notify() = 0;
virtual ~Subject() = default;
};
// 具体主题
class ConcreteSubject : public Subject {
std::vector<std::shared_ptr<Observer>> observers_;
std::string state_;
public:
void attach(std::shared_ptr<Observer> observer) override {
observers_.push_back(observer);
}
void detach(std::shared_ptr<Observer> observer) override {
observers_.erase(
std::remove(observers_.begin(), observers_.end(), observer),
observers_.end()
);
}
void notify() override {
for (const auto& observer : observers_) {
observer->update(state_);
}
}
void setState(const std::string& state) {
state_ = state;
std::cout << "主题状态改变: " << state_ << std::endl;
notify();
}
};
// 具体观察者
class ConcreteObserverA : public Observer {
public:
void update(const std::string& message) override {
std::cout << "观察者A 收到通知: " << message << std::endl;
}
};
class ConcreteObserverB : public Observer {
public:
void update(const std::string& message) override {
std::cout << "观察者B 收到通知: " << message << std::endl;
}
};
// 使用
ConcreteSubject subject;
auto observerA = std::make_shared<ConcreteObserverA>();
auto observerB = std::make_shared<ConcreteObserverB>();
subject.attach(observerA);
subject.attach(observerB);
subject.setState("新状态");
// 输出:
// 主题状态改变: 新状态
// 观察者A 收到通知: 新状态
// 观察者B 收到通知: 新状态
第二十一章:状态模式(State)
21.1 意图
允许一个对象在其内部状态改变时改变它的行为。
21.2 实现
cpp
// 状态接口
class State {
public:
virtual void handle() = 0;
virtual ~State() = default;
};
// 具体状态
class ConcreteStateA : public State {
public:
void handle() override {
std::cout << "状态A 处理中..." << std::endl;
}
};
class ConcreteStateB : public State {
public:
void handle() override {
std::cout << "状态B 处理中..." << std::endl;
}
};
// 上下文
class Context {
std::shared_ptr<State> state_;
public:
Context(std::shared_ptr<State> state) : state_(state) {}
void setState(std::shared_ptr<State> state) {
state_ = state;
std::cout << "切换到新状态" << std::endl;
}
void request() {
state_->handle();
}
};
// 使用
auto stateA = std::make_shared<ConcreteStateA>();
auto stateB = std::make_shared<ConcreteStateB>();
Context context(stateA);
context.request(); // "状态A 处理中..."
context.setState(stateB);
context.request(); // "状态B 处理中..."
第二十二章:策略模式(Strategy)
22.1 意图
定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。
22.2 实现
cpp
// 策略接口
class Strategy {
public:
virtual int execute(int a, int b) const = 0;
virtual ~Strategy() = default;
};
// 具体策略
class AddStrategy : public Strategy {
public:
int execute(int a, int b) const override { return a + b; }
};
class SubtractStrategy : public Strategy {
public:
int execute(int a, int b) const override { return a - b; }
};
class MultiplyStrategy : public Strategy {
public:
int execute(int a, int b) const override { return a * b; }
};
// 上下文
class Calculator {
std::shared_ptr<Strategy> strategy_;
public:
void setStrategy(std::shared_ptr<Strategy> strategy) {
strategy_ = strategy;
}
int calculate(int a, int b) const {
if (!strategy_) throw std::runtime_error("策略未设置");
return strategy_->execute(a, b);
}
};
// 使用
Calculator calc;
calc.setStrategy(std::make_shared<AddStrategy>());
std::cout << "10 + 5 = " << calc.calculate(10, 5) << std::endl; // 15
calc.setStrategy(std::make_shared<SubtractStrategy>());
std::cout << "10 - 5 = " << calc.calculate(10, 5) << std::endl; // 5
calc.setStrategy(std::make_shared<MultiplyStrategy>());
std::cout << "10 * 5 = " << calc.calculate(10, 5) << std::endl; // 50
第二十三章:模板方法模式(Template Method)
23.1 意图
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。
23.2 实现
cpp
// 抽象类
class AbstractClass {
public:
// 模板方法
void templateMethod() const {
baseOperation1();
requiredOperations1();
baseOperation2();
hook1();
requiredOperations2();
baseOperation3();
hook2();
}
// 基本操作(已经实现)
void baseOperation1() const {
std::cout << "AbstractClass: 基本操作1" << std::endl;
}
void baseOperation2() const {
std::cout << "AbstractClass: 基本操作2" << std::endl;
}
void baseOperation3() const {
std::cout << "AbstractClass: 基本操作3" << std::endl;
}
// 抽象操作(子类必须实现)
virtual void requiredOperations1() const = 0;
virtual void requiredOperations2() const = 0;
// 钩子(子类可选实现)
virtual void hook1() const {}
virtual void hook2() const {}
virtual ~AbstractClass() = default;
};
// 具体类
class ConcreteClass1 : public AbstractClass {
public:
void requiredOperations1() const override {
std::cout << "ConcreteClass1: 必要操作1" << std::endl;
}
void requiredOperations2() const override {
std::cout << "ConcreteClass1: 必要操作2" << std::endl;
}
void hook1() const override {
std::cout << "ConcreteClass1: 钩子1" << std::endl;
}
};
class ConcreteClass2 : public AbstractClass {
public:
void requiredOperations1() const override {
std::cout << "ConcreteClass2: 必要操作1" << std::endl;
}
void requiredOperations2() const override {
std::cout << "ConcreteClass2: 必要操作2" << std::endl;
}
void hook2() const override {
std::cout << "ConcreteClass2: 钩子2" << std::endl;
}
};
// 使用
void clientCode(const AbstractClass& obj) {
obj.templateMethod();
}
ConcreteClass1 obj1;
clientCode(obj1);
ConcreteClass2 obj2;
clientCode(obj2);
第二十四章:访问者模式(Visitor)
24.1 意图
表示一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
24.2 实现
cpp
// 前向声明
class ConcreteElementA;
class ConcreteElementB;
// 访问者接口
class Visitor {
public:
virtual void visitElementA(const ConcreteElementA& element) const = 0;
virtual void visitElementB(const ConcreteElementB& element) const = 0;
virtual ~Visitor() = default;
};
// 元素接口
class Element {
public:
virtual void accept(const Visitor& visitor) const = 0;
virtual ~Element() = default;
};
// 具体元素
class ConcreteElementA : public Element {
std::string data_;
public:
ConcreteElementA(const std::string& data) : data_(data) {}
const std::string& getData() const { return data_; }
void accept(const Visitor& visitor) const override {
visitor.visitElementA(*this);
}
};
class ConcreteElementB : public Element {
int value_;
public:
ConcreteElementB(int value) : value_(value) {}
int getValue() const { return value_; }
void accept(const Visitor& visitor) const override {
visitor.visitElementB(*this);
}
};
// 具体访问者
class PrintVisitor : public Visitor {
public:
void visitElementA(const ConcreteElementA& element) const override {
std::cout << "打印 ElementA: " << element.getData() << std::endl;
}
void visitElementB(const ConcreteElementB& element) const override {
std::cout << "打印 ElementB: " << element.getValue() << std::endl;
}
};
class ExportVisitor : public Visitor {
public:
void visitElementA(const ConcreteElementA& element) const override {
std::cout << "导出 ElementA: " << element.getData() << std::endl;
}
void visitElementB(const ConcreteElementB& element) const override {
std::cout << "导出 ElementB: " << element.getValue() << std::endl;
}
};
// 对象结构
class ObjectStructure {
std::vector<std::shared_ptr<Element>> elements_;
public:
void add(std::shared_ptr<Element> element) {
elements_.push_back(element);
}
void accept(const Visitor& visitor) const {
for (const auto& element : elements_) {
element->accept(visitor);
}
}
};
// 使用
ObjectStructure structure;
structure.add(std::make_shared<ConcreteElementA>("数据1"));
structure.add(std::make_shared<ConcreteElementB>(42));
structure.add(std::make_shared<ConcreteElementA>("数据2"));
PrintVisitor printVisitor;
structure.accept(printVisitor);
// 输出:
// 打印 ElementA: 数据1
// 打印 ElementB: 42
// 打印 ElementA: 数据2
ExportVisitor exportVisitor;
structure.accept(exportVisitor);
附录:设计模式速查表
A.1 创建型模式
| 模式 | 意图 | 关键类 |
|---|---|---|
| 单例 | 唯一实例 | static getInstance() |
| 工厂方法 | 创建对象延迟到子类 | virtual create() |
| 抽象工厂 | 创建一系列相关对象 | AbstractFactory |
| 建造者 | 分步构建复杂对象 | Builder, Director |
| 原型 | 通过拷贝创建对象 | clone() |
A.2 结构型模式
| 模式 | 意图 | 关键类 |
|---|---|---|
| 适配器 | 接口转换 | Adapter |
| 桥接 | 抽象与实现分离 | Abstraction, Implementation |
| 组合 | 树形结构 | Component, Composite, Leaf |
| 装饰器 | 动态添加职责 | Decorator |
| 外观 | 简化子系统接口 | Facade |
| 享元 | 共享细粒度对象 | Flyweight, FlyweightFactory |
| 代理 | 控制访问 | Proxy |
A.3 行为型模式
| 模式 | 意图 | 关键类 |
|---|---|---|
| 责任链 | 请求传递 | Handler |
| 命令 | 请求封装为对象 | Command, Receiver |
| 迭代器 | 顺序访问元素 | Iterator |
| 中介者 | 对象交互封装 | Mediator, Colleague |
| 备忘录 | 保存/恢复状态 | Memento, Caretaker |
| 观察者 | 一对多依赖 | Subject, Observer |
| 状态 | 状态改变行为 | State, Context |
| 策略 | 算法封装 | Strategy |
| 模板方法 | 算法骨架 | AbstractClass |
| 访问者 | 作用于元素的操作 | Visitor, Element |