c++最常用的几种设计模式

在 C++ 里,最"接地气"、面试问得最多、代码里真正天天能见到的,其实集中在下面 6 种。掌握它们就能覆盖 80% 的日常设计场景。

模式 一句话场景 C++ 惯用法要点 最常用变种
1. Singleton "全局只有一个"------日志、配置、显卡设备 1) 私构造+私赋值+公静态 Instance() 2) Meyers' Singleton(static 局部变量)线程安全又简洁 双检锁 DCLP(C++11 之后基本被 Meyers 取代)
2. Factory Method / Abstract Factory "new 太痛苦,对象类型运行时才知道"------UI 控件、数据库驱动 1) 基类提供 CreateXxx() 虚函数,返回 unique_ptr<Base> Simple Factory(一个静态 Create)
3. Observer "一对多松耦合通知"------MVC、事件总线、消息队列 1) 基类 IObserver 带纯虚 notify() 2) 用 vector<weak_ptr<IObserver> Signal/Slot(Qt、boost::signals2)
4. Strategy "算法一族随便换"------排序、压缩、支付渠道 1) 把算法封装成继承自 Strategy 的子类 2) 上下文存 unique_ptr<Strategy> Policy-based design(模板+编译期多态)
5. RAII / Wrapper(语言级模式) "资源释放一定走析构"------内存、锁、句柄 1) 构造里获取,析构里释放 2) 禁用拷贝或采用移动语义 unique_ptr/shared_ptr、lock_guard、fstream
6. Pimpl(编译防火墙) "头文件不动,实现随便改"------库开发 1) 类内只留 struct Impl; std::unique_ptr<Impl> pImpl;

1. Singleton( Meyers 版 )

cpp 复制代码
class Config {
public:
    static Config& instance() {
        static Config cfg;        // C++11 保证线程安全
        return cfg;
    }
    Config(const Config&) = delete;
    Config& operator=(const Config&) = delete;
private:
    Config() = default;
};

用法:Config::instance().get("timeout");

2. Factory 示例

cpp 复制代码
class Shape { public: virtual void draw() = 0; };
class Circle : public Shape { void draw() override {} };

using ShapePtr = std::unique_ptr<Shape>;
using Factory  = std::function<ShapePtr()>;

inline ShapePtr make_circle() { return std::make_unique<Circle>(); }

static std::unordered_map<std::string, Factory> g_reg = {
    {"circle", make_circle}
};

ShapePtr shape_factory(const std::string& key){
    return g_reg.at(key)();
}

调用:auto p = shape_factory("circle");

3. Observer 示例(weak_ptr 防悬空)

cpp 复制代码
class IObserver { public: virtual void onEvent() = 0; };

class Subject {
    std::vector<std::weak_ptr<IObserver>> subs;
public:
    void subscribe(std::shared_ptr<IObserver> o){
        subs.emplace_back(o);
    }
    void notify(){
        for (auto it = subs.begin(); it != subs.end(); ) {
            if (auto s = it->lock()) { s->onEvent(); ++it; }
            else                     { it = subs.erase(it); }
        }
    }
};

4. Strategy 示例

cpp 复制代码
class PayStrategy { public: virtual void pay(int cents) = 0; };
class AliPay : public PayStrategy { void pay(int) override {} };
class WechatPay : public PayStrategy { void pay(int) override {} };

class Order {
    std::unique_ptr<PayStrategy> strategy;
public:
    void set_pay(std::unique_ptr<PayStrategy> s){ strategy = std::move(s); }
    void checkout(int cents){ strategy->pay(cents); }
};

5. RAII / Wrapper

cpp 复制代码
std::unique_ptr<FILE, decltype(&fclose)>
make_file(const char* name){
    return {std::fopen(name,"w"), &fclose};
}

6. Pimpl

cpp 复制代码
// ====== Foo.h ======
class Foo {
public:
    Foo();
    ~Foo();
    void work();
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};

// ====== Foo.cpp ======
struct Foo::Impl {
    void workImpl() { /* 真正实现 */ }
};
Foo::Foo() : pImpl(std::make_unique<Impl>()) {}
Foo::~Foo() = default;          // 必须在 cpp 里,因为 Impl 完整类型在此处才可见
void Foo::work() { pImpl->workImpl(); }
  • 单例、工厂、观察者、策略 是"最常被问"的四大行为/创建模式。
相关推荐
进击的小头3 小时前
设计模式组合应用:嵌入式通信协议栈
c语言·设计模式·策略模式
致Great3 小时前
智能体的设计模式探讨
设计模式
BD_Marathon5 小时前
设计模式——单一职责原则
设计模式·单一职责原则
stevenzqzq5 小时前
Slot API 设计模式
设计模式·compose
reddingtons5 小时前
Cascadeur:动态总是“飘”?“物理外挂流” 3分钟直出重力感 2D 立绘
游戏·设计模式·aigc·设计师·游戏策划·游戏美术·cascadeur
Wyy_9527*5 小时前
行为型设计模式——策略模式
设计模式·策略模式
kogorou0105-bit6 小时前
前端设计模式:发布订阅与依赖倒置的解耦之道
前端·设计模式·面试·状态模式
BD_Marathon6 小时前
设计模式——接口隔离原则
java·设计模式·接口隔离原则
小码过河.1 天前
设计模式——适配器模式
设计模式·适配器模式
钝挫力PROGRAMER1 天前
软件工程结构型设计模式
设计模式·软件工程