当前位置: 首页> 财经> 访谈 > 建站工具 phpwind_天津站内关键词优化_交换链接的方法_百度趋势搜索大数据

建站工具 phpwind_天津站内关键词优化_交换链接的方法_百度趋势搜索大数据

时间:2025/8/9 13:04:09来源:https://blog.csdn.net/Dontla/article/details/146124715 浏览次数:0次
建站工具 phpwind_天津站内关键词优化_交换链接的方法_百度趋势搜索大数据

文章目录

      • 一、**创建型模式**(简化对象创建)
        • 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;}
};

总结:何时选用哪些模式?

场景推荐模式
需要隔离对象创建细节工厂模式、建造者模式
全局唯一访问点配置单例模式 (谨慎使用)
统一处理树形结构组合模式
动态增减对象功能装饰器模式
跨平台接口适配适配器模式、桥接模式
事件驱动系统观察者模式、发布-订阅模式
算法灵活替换策略模式、模板方法模式

设计模式的本质是 代码结构的经验总结,根据具体需求灵活选用,切勿过度设计!

关键字:建站工具 phpwind_天津站内关键词优化_交换链接的方法_百度趋势搜索大数据

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: