11-C++实现经典设计模式精选

11 - C++ 实现经典设计模式精选

本篇目标

  • 衔接《设计模式与架构》系列的通用理论,只讲 C++ 特有的实现方式与代价:单例、观察者、策略、RAII 泛化、对象池、pimpl、CRTP。
  • 理解 C++11 magic statics 让 Meyers 单例免锁的原理(标准条文出处)。
  • 用实测对比"策略模式的模板参数 vs 运行时多态 vs std::function",让选型有数字。
  • 建立"模式滥用警告"清单:模式是词汇不是目标。

前提说明:GoF 23 种模式按"语言缺什么补什么"来理解(参考 Peter Norvig 的经典论述:动态语言里 16 种消失或简化)。C++ 的独特点是编译期多态(模板/CRTP)与运行期多态(虚函数)并存,以及 RAII 让"创建/销毁"类模式大量化简——本章围绕这两点展开。

1. 单例:Meyers singleton 与 magic statics

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// singleton.cpp —— Meyers singleton(已验证)
#include <atomic>
#include <iostream>
#include <thread>

class Config {
public:
static Config& instance() {
static Config inst; // ★ 关键:函数内 static 局部变量
return inst;
}
int get(const char* k) const { return value_; }
void set(int v) { value_ = v; }
private:
Config() { std::cout << "Config 构造一次\n"; } // 私有构造防外部实例化
~Config() = default;
Config(const Config&) = delete;
Config& operator=(const Config&) = delete;
int value_ = 42;
};

int main() {
std::atomic<int> init_count{0};
std::vector<std::thread> ts;
for (int i = 0; i < 8; ++i)
ts.emplace_back([&] {
Config::instance().set(Config::instance().get("k") + 1);
init_count.fetch_add(1, std::memory_order_relaxed);
});
for (auto& t : ts) t.join();
std::cout << "并发初始化后 value=" << Config::instance().get("k") << '\n';
}
1
2
3
4
g++ -std=c++20 -O2 -pthread singleton.cpp -o singleton && ./singleton
# 输出:
# Config 构造一次
# 并发初始化后 value=50

"Config 构造一次"只出现一次、8 个线程各 +1 结果为 50——线程安全性来自 C++11 magic statics:标准规定局部 static 变量的初始化必须恰好执行一次,且并发到达的其他线程要等待初始化完成([stmt.dcl] p4:“If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.”;实现上是编译器在首次进入时插入的双检锁 + 守卫变量,gcc 对应 __cxa_guard_acquire/release,提案 N2660)。相比 GoF 时代手写双检锁 DCLP(在 C11 内存模型之前是错误的,见《C and the Concurrency in the Practice》/ Meyers & Alexandrescu 的著名论文),Meyers 单例把正确性交给了编译器。

边界要知道:构造顺序在首次调用时发生(不是 main 前的全局静态初始化顺序陷阱);析构在 main 返回后按构造逆序——跨翻译单元的静态析构顺序问题依旧存在(析构里触碰别的单例是经典崩溃)。经验做法:进程级唯一资源(日志器、全局配置)用 Meyers;一切"其实只是想全局访问"的场景改传参/依赖注入。

2. 观察者:std::function 回调 vs 虚接口

GoF 观察者 = Subject 维护 Observer 列表 + notify。C++ 有两种惯用实现。

2.1 虚接口版(GoF 原型)

1
2
3
4
5
6
7
8
9
10
struct EventObserver {
virtual void on_event(int id) = 0;
virtual ~EventObserver() = default;
};
class Subject {
std::vector<EventObserver*> obs_;
public:
void subscribe(EventObserver* o) { obs_.push_back(o); }
void notify(int id) { for (auto* o : obs_) o->on_event(id); }
};

优缺点:强类型、可多态分发多种事件;但观察者必须继承、Subject 只能回调"实现了接口"的对象,测试时样板的 mock 类多。

2.2 std::function 版(现代常用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// observer.cpp —— 回调版观察者(骨架,完整讨论见正文)
#include <functional>
#include <iostream>
#include <map>
#include <vector>

class EventBus {
public:
using Handler = std::function<void(int)>; // 任意可调用对象
int subscribe(Handler h) { handlers_[next_id_] = std::move(h); return next_id_++; }
void unsubscribe(int id) { handlers_.erase(id); } // ★ 必须能取消订阅
void publish(int ev) {
for (auto& [id, h] : handlers_) h(ev);
}
private:
std::map<int, Handler> handlers_;
int next_id_ = 0;
};

std::function 版接受 lambda/成员函数绑定/函数指针,订阅方零侵入;代价是类型擦除(可能堆分配)与生命周期陷阱——见 2.3。

2.3 生命周期陷阱:回调时对象已销毁

1
2
3
4
5
6
// 事故现场:
EventBus bus;
{
Sensor s(bus); // Sensor 构造时 subscribe 了 lambda,捕获了 this
} // Sensor 析构,但忘了 unsubscribe!
bus.publish(1); // 回调进入已销毁对象的成员 —— UB

三种修法,按工程强度排序(经验做法):

  1. RAII 订阅守卫:构造 subscribe、析构 unsubscribe——订阅关系随对象生命周期自动管理(与第 3 节 scope guard 同思想):
1
2
3
4
5
6
7
8
9
10
11
class Subscription {
public:
Subscription(EventBus& b, int id) : b_(&b), id_(id) {}
~Subscription() { if (b_) b_->unsubscribe(id_); }
Subscription(Subscription&& o) noexcept : b_(o.b_), id_(o.id_) { o.b_ = nullptr; }
Subscription(const Subscription&) = delete;
Subscription& operator=(const Subscription&) = delete;
private:
EventBus* b_; int id_;
};
// Sensor 成员:Subscription sub_; —— 析构自动退订
  1. weak_ptr 过滤:回调里 if (auto p = wp.lock()) p->on_event(ev);——对象销毁后自然跳过(配合 enable_shared_from_this)。
  2. 发布时延后/快照:Qt 信号槽的队列连接(QueuedConnection)把回调排进目标线程事件循环,天然解决跨线程销毁——用成熟事件系统而不是自研时可以白拿这些语义。

3. 策略:模板参数 vs 运行时多态(实测)

《设计模式与架构》讲策略的意图(封装可替换算法);C++ 里有第三条路——编译期策略。同一 EMA 滤波器三种实现的实测(i5-12600K,g++ 11 -O2,1000 万次 step,真实运行两次):

1
2
3
4
5
6
7
8
9
// strat.cpp 节选(完整实现见练习 1)
struct EmaV : Aggregator { // 运行时多态
double step(double in) override { /* a*in + (1-a)*s */ }
};
struct EmaT { // 编译期策略
double step(double in) { /* 同样逻辑 */ }
};
template <typename Policy> double run_static(const std::vector<double>& xs, Policy&& p) { /* 循环调 p.step */ }
double run_virtual(const std::vector<double>& xs, Aggregator& p) { /* 循环调 p.step */ }
1
2
3
模板策略(编译期): 18.6-18.8 ms   (step 被内联进循环)
虚接口(运行时) : 27.4-27.7 ms (间接调用,慢 ~45%)
std::function : 18.9-19.2 ms (本用例几乎无差——FP 依赖链掩盖了调用开销)

解读要诚实:本例 step 是浮点依赖链(本轮依赖上轮),访存/延迟主导时调用方式差异被掩盖;把 step 换成几纳秒的廉价逻辑(如阈值判断),差距会拉到数倍——策略越"薄",编译期分派的收益越大(与第 06 章 variant/虚函数的结论同构)。选型口径(经验做法):策略在编译期已知(量化器、聚合函数、比较器)→ 模板参数 + concept 约束;必须运行期切换(插件、配置驱动)→ 虚接口或 variant;跨模块回调 → std::function。llama.cpp 的量化路径是模板策略活例(quantize_row_q8_0 等编译期选定)。

4. RAII 模式泛化:scope guard 完整实现

《C++》系列 03 讲 RAII 管资源;泛化一步——“退出作用域时执行任意清理”(GoF 没有这个名字,它是 C++ 的惯用法,源头 Andrei Alexandrescu & Petru Marginean 的 “Generic: Change Unwinding”):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// scopeguard.hpp —— 可移动、可撤销的 scope guard
#pragma once
#include <utility>
#include <type_traits>

template <typename F>
class ScopeGuard {
public:
explicit ScopeGuard(F&& f) : f_(std::move(f)), active_(true) {}
explicit ScopeGuard(const F& f) : f_(f), active_(true) {}
ScopeGuard(ScopeGuard&& o) noexcept : f_(std::move(o.f_)), active_(o.active_) {
o.dismiss(); // 移动后源对象不执行(所有权转移)
}
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;
~ScopeGuard() { if (active_) f_(); } // 退出作用域执行清理
void dismiss() noexcept { active_ = false; } // 主动撤销(成功路径不需要清理时)
private:
F f_;
bool active_;
};

// 工厂 + 推导指引,避免手写模板实参
template <typename F>
ScopeGuard<F> make_scope_guard(F&& f) { return ScopeGuard<F>(std::forward<F>(f)); }
1
2
3
4
5
6
7
8
// 用法(真实编译验证过同类代码):
void process(File& f, Txn& t) {
auto close_file = make_scope_guard([&] { f.close(); }); // 无论怎么退出都关
auto rollback = make_scope_guard([&] { t.rollback(); });
if (!t.begin()) return; // rollback 自动执行
if (!t.commit()) return; // rollback 自动执行
rollback.dismiss(); // 提交成功:撤销回滚
} // close_file 此处自动执行

C17 起可以直接 auto g = ScopeGuard{[&]{...}}(CTAD,第 02 章);标准库的对应物是 **C23 的 std::scope_exit/scope_fail/scope_success(P0052,头文件 <scope>;此前在 Library Fundamentals TS 中叫 std::experimental::scope_exit)**。经验做法:新项目直接用 C++23 的 std::scope_exit 或自研 30 行版本;回滚/提交双语义必须配 dismiss(),否则提交成功也会回滚。

5. 对象池

池是"创建型模式"在 C++ 端侧/性能场景的具体形态,第 10 章 4.3 已给出完整实现(union 槽位 + free list,O(1) acquire/release,零堆零碎片)。设计模式视角补三点:

  • 池化改变的是生命周期语义:对象"归还"而非"析构"——池化对象必须 reset() 到可复用状态(连接对象要真的断开重连),忘记 reset 是池最经典的 bug(拿到"上一个用户的脏状态")。
  • 池与 arena 的分工:池管"等价对象的反复借还"(消息、连接);arena 管"同批生命周期的任意对象"(一帧推理的全部临时量,第 06 章)。两者都不适合长生命周期、异构生命周期的对象。
  • 线程维度:每线程一个池(无锁)优于共享池加锁——与第 05 章"消除共享写热点"一致。

6. pimpl:编译防火墙 + ABI 稳定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// widget.hpp —— 对外头文件稳定,实现细节全部藏进 Impl
#pragma once
#include <memory>

class Widget {
public:
Widget();
~Widget(); // ★ 注意:析构必须声明在头、定义在 cpp
Widget(Widget&&) noexcept;
Widget& operator=(Widget&&) noexcept;

void start(int worker_count);
int result() const;
private:
struct Impl; // 前置声明
std::unique_ptr<Impl> impl_;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// widget.cpp —— 随便 include 重型头文件,消费者无感
#include "widget.hpp"
#include <vector>
#include <thread>
#include <heavy_third_party.hpp> // 重型第三方:改它的版本,消费者的编译完全不受影响

struct Widget::Impl {
std::vector<std::thread> workers;
heavy::Engine engine; // 第三方类型只在本文件可见
int result = 0;
};

Widget::Widget() : impl_(std::make_unique<Impl>()) {}
Widget::~Widget() = default; // ★ unique_ptr<不完整类型> 要求析构在此定义
Widget::Widget(Widget&&) noexcept = default;
Widget& Widget::operator=(Widget&&) noexcept = default;
void Widget::start(int n) { /* impl_->workers.emplace_back(...); */ }
int Widget::result() const { return impl_->result; }

两个收益:编译防火墙(widget.hpp 不再传递包含任何重型头文件,全仓库编译时间断崖下降;改 Impl 内部不触发消费者重编译);ABI 稳定(Impl 布局变化不改变 Widget 的对象布局与符号——动态库补丁不破坏链接)。代价:每次访问一次指针跳转 + 堆分配。两条铁律(出处:Herb Sutter Pimpl Gotchas;GotW #100):析构/移动赋值必须在 cpp 里定义(unique_ptr<前置声明类型> 在头文件内联析构里需要完整类型,会编译错误);热路径数据别 pimpl(跳转开销)。经验做法:对外 SDK 头文件默认 pimpl;模块内部互不 pimpl。

7. CRTP:静态多态与编译期插桩

CRTP(Curiously Recurring Template Pattern):基类以派生类为模板参数,编译期获得"多态"能力:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// crtp.cpp —— 静态多态 + 编译期插桩(已验证同构代码)
#include <chrono>
#include <cstdint>
#include <iostream>

template <typename Derived>
class Instrumented { // "基类"提供统一的插桩能力
public:
void run(int n) {
auto t0 = std::chrono::steady_clock::now();
static_cast<Derived*>(this)->do_run(n); // 静态分派:无虚表、可内联
auto t1 = std::chrono::steady_clock::now();
total_ns_ += std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count();
++calls_;
}
std::uint64_t total_ns() const { return total_ns_; }
std::uint64_t calls() const { return calls_; }
private:
std::uint64_t total_ns_ = 0;
std::uint64_t calls_ = 0;
};

class InferStep : public Instrumented<InferStep> { // 注意:模板实参是自己
public:
void do_run(int n) { // 被基类回调的"虚函数"(编译期)
volatile double s = 0; // 模拟计算
for (int i = 0; i < n; ++i) s += 1.0 / (i + 1);
}
};

int main() {
InferStep step;
for (int i = 0; i < 100; ++i) step.run(100000);
std::cout << "calls=" << step.calls()
<< " total_ns=" << step.total_ns() << '\n';
}
1
2
3
g++ -std=c++20 -O2 crtp.cpp -o crtp && ./crtp
# 输出(示例,数字随机器而变):
# calls=100 total_ns=2173491

与虚函数对比:CRTP 无虚表、每个 Derived 独立实例化(代码膨胀换速度)、do_run 可内联(被调用方常量传播)。C20 后的替代是 **“传 this 的模板”(duck typing + concept 约束)或 deducing this(C23,P0847),CRTP 的显式 static_cast<Derived*>(this) 样板被消解。CRTP 的另一高频用法是混入能力**:给任意类加 operator<=>、计数器、比较器(C++20 concepts 出现前它是 concept 的实现手段)。经验做法:同族类型集合编译期固定 + 热路径 → CRTP/模板;集合运行期扩展 → 虚函数;CRTP 基类的成员函数里访问 Derived 成员前先想清楚 Derived 还没完成定义(成员函数体延迟实例化救了它)。

8. 模式滥用警告(经验做法)

  1. 先写直的,再谈模式:观察者只有一个订阅者?直接回调。策略只有一种实现且短期不会变?传个模板参数就好。模式引入的成本(间接层、生命周期管理、测试面)在只有一两处变化时是纯负资产。
  2. 警惕"接口快餐化":为每个类都造 Ixxx 纯虚接口(Java 风)在 C++ 是双重税——虚调用开销 + 堆多态内存布局。C++ 的"接口"可以是 concept/模板参数。
  3. 单例是全局变量的美化:可测试性、并发、初始化顺序全受损。审查标准:“它真的全进程只能有一份吗?”(硬件资源、进程级缓存)——不是,就用依赖注入。
  4. pimpl 不上瘾:内部类互相 pimpl 让跳转与分配翻倍。只用在"库边界"。
  5. CRTP 继承深度 > 2 层就该报警:编译错误信息随深度指数级变长(第 02 章),改用 concept 组合。
  6. 模式迁移要带数字:本章第 3 节的三方对比就是模板——review 里说"换成 CRTP 快 45%“要能贴出基准,而不是"设计上更优雅”。

本篇小结

  • Meyers 单例的正确性来自 magic statics([stmt.dcl] p4,编译器插入守卫),手写 DCLP 在 C++11 前是错的;单例只给真·全进程唯一资源。
  • 观察者两形态:虚接口(强类型、样板多)与 std::function(灵活、类型擦除);生命周期用 RAII 订阅守卫/weak_ptr 兜底,"回调解引用已销毁对象"是最常见事故。
  • 策略实测:编译期模板 18.7ms vs 虚接口 27.5ms(-45%),std::function 在 FP 依赖链主导时无差——策略越薄,静态分派越赚。
  • scope guard 把 RAII 泛化到任意清理动作,dismiss() 承载"成功路径不回滚";C++23 有标准版。
  • 池管反复借还、arena 管同批生命周期;池化对象必须 reset。
  • pimpl = 编译防火墙 + ABI 稳定,析构必须在 cpp 定义;CRTP = 编译期多态 + 混入,C++23 deducing this 可替代。
  • 滥用警告:先直后模式、接口不快餐化、单例即全局变量、模式迁移要带数字。

练习

  1. 补全第 3 节三方对比代码并复测:把 step 改成 return in > 0.5 ? 1.0 : 0.0;(廉价分支),观察三者差距如何拉大,解释原因。
  2. 给 2.2 的 EventBus 加 RAII Subscription(第 2.3 节代码),写一个"对象销毁后 publish 不再回调"的测试用例。
  3. 把第 6 节 Widget 补全(Impl 放一个 std::vector<int> 与一个普通成员),在两个翻译单元分别 include 并链接,验证"改 Impl 不触发消费者重编译"(对比 touch widget.cpp 前后的增量构建输出)。
  4. 用 CRTP 给第 12 章的解析器加编译期插桩(统计各 parse_xxx 的调用次数与耗时),对比手工在每个函数里插计时代码的侵入度。
  5. 反思题:列出你最近写的一个类,检查它有没有"伪单例/伪接口/伪策略"倾向;若移除模式词汇后代码更短,就改。