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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| template<typename ObserverType> class Subject { vector<ObserverType*> _list; public: void subscribe(ObserverType* obs) { auto itor = std::find(_list.begin(), _list.end(), obs); if (_list.end() == itor) { _list.push_back(obs); } } void unSubscribe(ObserverType* obs) { _list.erase(std::remove(_list.begin(), _list.end(), obs)); }
template<typename FuncType> void publish(FuncType func) { for (auto obs : _list) { func(obs); } } };
class CatObserver { public: virtual void onMiaow() = 0; virtual ~CatObserver() {} };
class Tom : public Subject<CatObserver> { public: void miaow() { cout << "喵" << endl; publish(std::bind(&CatObserver::onMiaow, std::placeholders::_1)); } };
class Jerry : public CatObserver { public: void onMiaow() override { RunAway(); } void RunAway() { cout << "那只笨又猫来了,快跑!" << endl; } };
int main() { Tom tom; Jerry jerry1, jerry2, jerry3;
tom.subscribe(&jerry1); tom.subscribe(&jerry2); tom.subscribe(&jerry3); tom.miaow(); }
|