文章目录
- 一、**创建型模式**(简化对象创建)
- 1. **工厂模式**(Factory Pattern)
- 2. **单例模式**(Singleton Pattern)
- 3. **建造者模式**(Builder Pattern)
- 二、**结构型模式**(处理对象组合关系)
- 4. **适配器模式**(Adapter Pattern)
- 5. **组合模式**(Composite Pattern)
- 6. **代理模式**(Proxy Pattern - 如智能指针)
- 三、**行为型模式**(对象间的通信与职责分配)
- 7. **观察者模式**(Observer Pattern)
- 8. **策略模式**(Strategy Pattern)
- 9. **模板方法模式**(Template Method)
- 四、**C++ 特有模式**
- 10. **RAII 模式**(资源获取即初始化)
- 11. **CRTP 模式**(Curiously Recurring Template Pattern)
- 12. **PIMPL 惯用法**(减少头文件依赖)
- 五、**性能优化模式**
- 13. **对象池模式**(避免频繁创建销毁)
- 14. **惰性初始化模式**(延迟加载)
- **总结:何时选用哪些模式?**
C++ 中常用的设计模式与其独特语言特性(如手动内存管理、模板、运算符重载等)结合,可以简化复杂逻辑的代码实现,以下是 20 种核心设计模式(实际上不到20种) 及其典型 C++ 实现示例:
一、创建型模式(简化对象创建)
1. 工厂模式(Factory Pattern)
- 作用:解耦对象的创建逻辑与使用逻辑
- 代码示例:
class Shape { public:virtual ~Shape() = default;virtual void draw() = 0; }; class Circle : public Shape { /*...*/ }; class Square : public Shape { /*...*/ };class ShapeFactory { public:static Shape* createShape(const string& type) {if (type == "circle") return new Circle();else if (type == "square") return new Square();return nullptr;} };// 使用: Shape* obj = ShapeFactory::createShape("circle"); obj->draw();
2. 单例模式(Singleton Pattern)
- C++ 线程安全推荐实现:
class Singleton { private:static Singleton* instance;static mutex mtx;Singleton() {} // 私有化构造函数public:Singleton(const Singleton&) = delete;Singleton& operator=(const Singleton&) = delete;static Singleton* getInstance() {if (instance == nullptr) {lock_guard<mutex> lock(mtx); // 加锁if (instance == nullptr) { // 双重检查锁定instance = new Singleton();}}return instance;} };// 初始化静态成员: Singleton* Singleton::instance = nullptr; mutex Singleton::mtx;
3. 建造者模式(Builder Pattern)
- 适用场景:分步骤创建复杂对象(如 GUI 组件)
class Pizza { public:void setDough(const string& dough) { /*...*/ }void setSauce(const string& sauce) { /*...*/ } };class PizzaBuilder { public:virtual ~PizzaBuilder() = default;virtual void buildDough() = 0;virtual void buildSauce() = 0;virtual Pizza* getPizza() = 0; };class Chef { private:PizzaBuilder* builder; public:void makePizza(PizzaBuilder* b) {builder = b;b->buildDough();b->buildSauce();} };
二、结构型模式(处理对象组合关系)
4. 适配器模式(Adapter Pattern)
- 用途:转换接口以兼容旧代码
class LegacyRectangle { // 旧接口: 通过坐标画矩形 public:void draw(int x1, int y1, int x2, int y2) { /*...*/ } };class RectangleAdapter : public Shape { private:LegacyRectangle adaptee; public:void draw() override { adaptee.draw(0, 0, 100, 100); // 适配到新接口} };
5. 组合模式(Composite Pattern)
- 树形结构示例:
class Component { public:virtual ~Component() = default;virtual void operation() = 0;virtual void add(Component* c) {} // 默认空实现 };class Leaf : public Component { public:void operation() override { /*处理叶子节点*/ } };class Composite : public Component { private:vector<Component*> children; public:void operation() override {for (auto& child : children) {child->operation(); // 递归调用子节点}}void add(Component* c) override { children.push_back(c); } };
6. 代理模式(Proxy Pattern - 如智能指针)
- 通过 RAII 管理资源:
template <typename T> class SmartPointer { private:T* raw_ptr; public:explicit SmartPointer(T* ptr) : raw_ptr(ptr) {}~SmartPointer() { delete raw_ptr; }T* operator->() { return raw_ptr; } // 代理指针运算符 };// 使用: SmartPointer<MyClass> ptr(new MyClass()); ptr->doSomething(); // 自动释放内存
三、行为型模式(对象间的通信与职责分配)
7. 观察者模式(Observer Pattern)
- 基于 C++11 的现代化实现:
#include <functional> #include <vector>class Subject { private:vector<function<void(int)>> observers; public:void attach(const function<void(int)>& obs) {observers.push_back(obs);}void notify(int value) {for (auto& obs : observers) {obs(value); // 通知所有观察者}} };// 使用 lambda: Subject subject; subject.attach([](int val) { cout << "Observer1: " << val << endl; }); subject.notify(42);
8. 策略模式(Strategy Pattern)
- 结合模板与函数对象:
template <typename T> class SortStrategy { public:virtual void sort(vector<T>& data) = 0; };class QuickSort : public SortStrategy<int> { public:void sort(vector<int>& data) override { /*快速排序实现*/ } };class Context { private:SortStrategy<int>* strategy; public:void setStrategy(SortStrategy<int>* s) { strategy = s; }void execute(vector<int>& data) { strategy->sort(data); } };
9. 模板方法模式(Template Method)
- 代码骨架延迟实现:
class DataProcessor { public:void process() {loadData();analyze(); // 子类实现差异点saveResult();} protected:virtual void analyze() = 0;void loadData() { /*通用加载逻辑*/ }void saveResult() { /*通用保存逻辑*/ } };class AudioProcessor : public DataProcessor { protected:void analyze() override { /*音频分析算法*/ } };
四、C++ 特有模式
10. RAII 模式(资源获取即初始化)
- 核心思想:通过对象生命周期自动管理资源(内存、文件、锁)
class FileWrapper { private:FILE* file; public:explicit FileWrapper(const char* filename) : file(fopen(filename, "r")) {}~FileWrapper() { if (file) fclose(file); }// 禁用拷贝(或实现移动语义)FileWrapper(const FileWrapper&) = delete;FileWrapper& operator=(const FileWrapper&) = delete; };// 使用: {FileWrapper file("data.txt"); // 文件自动关闭 }
11. CRTP 模式(Curiously Recurring Template Pattern)
- 静态多态优化性能:
template <typename Derived> class Base { public:void interface() {static_cast<Derived*>(this)->implementation();} };class Derived : public Base<Derived> { public:void implementation() { /*子类具体实现*/ } };// 调用: Derived d; d.interface(); // 调用Derived的实现,无虚函数开销
12. PIMPL 惯用法(减少头文件依赖)
- 隐藏实现细节:
// Widget.h class Widget { public:Widget();~Widget();void doSomething(); private:struct Impl; // 前向声明unique_ptr<Impl> pImpl; // 实现细节隐藏 };// Widget.cpp struct Widget::Impl {int internalData;void helperFunction() { /*私有函数实现*/ } };Widget::Widget() : pImpl(make_unique<Impl>()) {} Widget::~Widget() = default; // 需在cpp中定义(因unique_ptr删除不完整类型)
五、性能优化模式
13. 对象池模式(避免频繁创建销毁)
template <typename T>
class ObjectPool {
private:queue<unique_ptr<T>> pool;
public:T* acquire() {if (pool.empty()) {return new T();}auto obj = std::move(pool.front());pool.pop();return obj.release();}void release(T* obj) {pool.push(unique_ptr<T>(obj)); // 重用对象}
};
14. 惰性初始化模式(延迟加载)
class HeavyResource {
private:vector<BigData>* data = nullptr;
public:vector<BigData>& getData() {if (data == nullptr) {data = new vector<BigData>(/*加载大量数据*/);}return *data;}
};
总结:何时选用哪些模式?
场景 | 推荐模式 |
---|---|
需要隔离对象创建细节 | 工厂模式、建造者模式 |
全局唯一访问点配置 | 单例模式 (谨慎使用) |
统一处理树形结构 | 组合模式 |
动态增减对象功能 | 装饰器模式 |
跨平台接口适配 | 适配器模式、桥接模式 |
事件驱动系统 | 观察者模式、发布-订阅模式 |
算法灵活替换 | 策略模式、模板方法模式 |
设计模式的本质是 代码结构的经验总结,根据具体需求灵活选用,切勿过度设计!