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 版 )
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 示例
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 防悬空)
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 示例
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
std::unique_ptr<FILE, decltype(&fclose)>
make_file(const char* name){return {std::fopen(name,"w"), &fclose};
}
6. Pimpl
// ====== 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(); }
单例、工厂、观察者、策略 是“最常被问”的四大行为/创建模式。