c++设计模式之观察者模式
作者:互联网
视频地址:
https://www.ixigua.com/6804249883344634380?id=6803643021414892046
文档整理地址:
1 #include<iostream> 2 #include <algorithm> 3 #include <string> 4 #include <list> 5 #include <memory> 6 using namespace std; 7 8 enum class Position 9 { 10 CPP, 11 JAVA, 12 PHP, 13 C_Sharp, 14 Python 15 }; 16 17 class Engineer 18 { 19 public: 20 Engineer(const string &name) :name_(name) {}; 21 virtual void update(Position position) = 0; 22 protected: 23 string name_; 24 25 }; 26 27 class CppEngineer:public Engineer 28 { 29 public: 30 CppEngineer(const string &name) :Engineer(name) {}; 31 virtual void update(Position position)override 32 { 33 if (position == Position::CPP) 34 { 35 cout << name_ << " 投递简历!" << endl; 36 } 37 } 38 }; 39 40 class PHPEngineer :public Engineer 41 { 42 public: 43 PHPEngineer(const string&name) :Engineer(name) {}; 44 virtual void update(Position position)override 45 { 46 if (position == Position::PHP) 47 { 48 cout << name_ << " 投递简历!" << endl; 49 } 50 } 51 }; 52 53 class JAVAEngineer :public Engineer 54 { 55 public: 56 JAVAEngineer(const string&name) :Engineer(name) {}; 57 virtual void update(Position position)override 58 { 59 if (position == Position::JAVA) 60 { 61 cout << name_ << " 投递简历!" << endl; 62 } 63 } 64 }; 65 66 67 68 class Alibaba 69 { 70 public: 71 void Recruit(Position position) //招聘某种职位 72 { 73 Notify(position); 74 } 75 void AddEngineer(shared_ptr<Engineer> engineer) 76 { 77 engineer_list.push_back(engineer); 78 } 79 private: 80 list<shared_ptr<Engineer>> engineer_list; 81 void Notify(Position position) //通知 82 { 83 for (const auto &engineer : engineer_list) 84 { 85 engineer->update(position); 86 } 87 } 88 }; 89 90 int main() 91 { 92 Alibaba ali; 93 ali.AddEngineer(make_shared<CppEngineer>("C++程序员")); 94 ali.AddEngineer(make_shared<JAVAEngineer>("Java程序员")); 95 ali.AddEngineer(make_shared<PHPEngineer>("PHP程序员")); 96 97 ali.Recruit(Position::CPP); 98 ali.Recruit(Position::Python); 99 ali.Recruit(Position::C_Sharp); 100 ali.Recruit(Position::PHP); 101 }
观察者模式:
标签:include,name,ali,观察者,c++,position,Position,设计模式,engineer 来源: https://www.cnblogs.com/MGFangel/p/16283096.html