Spy on enemy.
使用这个模式可以根据某些事件自动更新。
设计思路:
1 设计一个基类,作为需要观察一个时间行为的接口类
2 设计一个观察者类,可以观察所有基类的衍生类, 这里使用set来保存这些需要更新的类。
一个事件相当于一个函数,事件发生(调用函数)同时自动调用需要更新的函数动作。
#pragma once #include <iostream> #include <string> #include <set> #include <vector> using namespace std; class Observer_Enemy { public: virtual void update(string name) = 0; }; class Watcher_Enemy { public: virtual void registerObserver(Observer_Enemy *ob) = 0; virtual void removeObserver(Observer_Enemy *ob) =0; virtual void notifyObserver() = 0; }; class SpyOnEnemy : public Watcher_Enemy { set<Observer_Enemy *> obs; string enemy; public: SpyOnEnemy():obs(), enemy() { } void registerObserver(Observer_Enemy *ob) { obs.insert(ob); } void enemyMove(string en) { enemy = en; notifyObserver(); } void notifyObserver() { for (auto x:obs) { x->update(enemy); } } void removeObserver(Observer_Enemy *ob) { obs.erase(ob); } }; class airForce : public Observer_Enemy { public: void update(string n) { cout<<"\nEnemy "<<n<<" move.\n" <<"AirForce get ready, moving out...\n"; } }; class Marine : public Observer_Enemy { public: void update(string n) { cout<<"\nEnemy "<<n<<" move.\n" <<"Marine take action...\n"; } }; class Tank : public Observer_Enemy { public: void update(string n) { cout<<"\nEnemy "<<n<<" move.\n" <<"Tank is ready, rolling...\n"; } }; void ObserVer_Enemy_Run() { airForce airforce; Marine marine; Tank tank; SpyOnEnemy watcher; watcher.registerObserver(&airforce); watcher.registerObserver(&marine); watcher.registerObserver(&tank); string enemy; while (getline(cin, enemy)) { watcher.enemyMove(enemy); } watcher.removeObserver(&airforce); watcher.enemyMove("The Last Soilder"); }
运行:
Design Pattern - Observer 观察者设计模式
时间: 2024-10-11 11:58:05