分享一段优雅的代码,测试编译通过。摘自《设计模式沉思录》,稍作修改,否则编译不过

本文介绍了一个使用C++实现的模板事件通知系统。该系统通过泛型编程的方式定义了一种事件处理机制,允许不同类型的事件(如硬币插入、释放及商品分配等)注册多个处理器,并在事件发生时调用这些处理器进行相应操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include #include #include using namespace std;template class TEvent{public:class Handler{public:Handler(){registry.push_back(this);}virtual int handleEvent(const T& t) = 0;};static void notify (TEvent* t);void Notify(){T::notify(this);}typedef list HandlerList;private:static HandlerList registry;};template void TEvent::notify (TEvent* t){typename HandlerList::iterator i;for(i = registry.begin(); i != registry.end(); i ++){(*i)->handleEvent(* (T*) t);}}template typename TEvent::HandlerList TEvent::registry;class CoinInsertedEvent : public TEvent{};class CoinReleaseEvent : public TEvent{};class ProductDispenseEvent : public TEvent {};class CoinChanger:public CoinReleaseEvent :: Handler,public ProductDispenseEvent :: Handler{public:int handleEvent(const ProductDispenseEvent& event){cout<<"changer:: coin dispensed"<<endl;return 0;}int handleEvent(const CoinReleaseEvent& event){cout<<"changer:: coin released"<<endl;return 0;}};int main(){CoinReleaseEvent coinReleaseEvent;CoinChanger coinChanger;ProductDispenseEvent productDispenseEvent;coinReleaseEvent.Notify();productDispenseEvent.Notify();}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值