设计模式5——观察者模式
观察这模式中,有一个观察者监听一个事件,当事件发生时,向所有被通知者发送相应的消息和命令。
例如,秘书作为观察者,监听老板的动作。当老板回来时,向看电影、睡觉的员工发送消息,让他们停止并开始工作。
Observation.h内容
1 #ifndef Observation_H_H 2 #define Observation_H_H 3 4 #include <iostream> 5 #include <vector> 6 using namespace std; 7 8 class Secretary; 9 10 class Boss 11 { 12 public: 13 Boss(); 14 void comeBack(); 15 void setSecretary(Secretary *secretary0); 16 private: 17 Secretary *secretary; 18 }; 19 20 class Staff 21 { 22 public: 23 virtual void getSingal() = 0; 24 virtual ~Staff() {} 25 }; 26 27 class StaffMovie : public Staff 28 { 29 public: 30 virtual void getSingal() { cout << "Boss is coming, Stop watching movie!" << endl; } 31 }; 32 33 class StaffSleep : public Staff 34 { 35 public: 36 virtual void getSingal() { cout << "Boss is coming, Stop sleeping!" << endl; } 37 }; 38 39 class Secretary 40 { 41 public: 42 Secretary() : boss(NULL) {} 43 void sendSingal(){ 44 for(size_t i=0; i<vecStaff.size(); ++i){ 45 vecStaff[i]->getSingal(); 46 } 47 } 48 49 void addStaff(Staff *staff) { vecStaff.push_back(staff); } 50 void setBoss(Boss *boss0) { boss = boss0; } 51 private: 52 Boss *boss; 53 vector<Staff*> vecStaff; 54 }; 55 56 57 Boss::Boss() : secretary(NULL) {} 58 void Boss::comeBack() { secretary->sendSingal(); } 59 void Boss::setSecretary(Secretary *secretary0) { secretary = secretary0; } 60 61 void ObservationTest() 62 { 63 Boss *boss = new Boss(); 64 Staff *staff1 = new StaffMovie(); 65 Staff *staff2 = new StaffSleep(); 66 Secretary *secretary = new Secretary(); 67 secretary->addStaff(staff1); 68 secretary->addStaff(staff2); 69 secretary->setBoss(boss); 70 boss->setSecretary(secretary); 71 72 boss->comeBack(); 73 } 74 75 #endif
运行结果: