访问模式(visitor)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 //访问者模式:核心叫做双重分发:两个多态:accept,visit 6 7 class XiaoMi; 8 class HuaWei; 9 class Oppo; 10 class CellPhoneVisitor { 11 public: 12 virtual void visit(XiaoMi* p) = 0; 13 virtual void visit(HuaWei* p) = 0; 14 virtual void visit(Oppo* p) = 0; 15 protected: 16 CellPhoneVisitor(){} 17 }; 18 19 20 class CellPhone { 21 public: 22 virtual void dial() = 0; 23 virtual void sendMsg() = 0; 24 virtual void hang() = 0; 25 virtual void recvMsg() = 0; 26 virtual void accept(CellPhoneVisitor* p) = 0; 27 //Solaris系统--> 28 //Win7/win10 29 //Mac 30 protected: 31 CellPhone(){} 32 }; 33 34 class XiaoMi :public CellPhone { 35 public: 36 void dial() { cout << "小米" << "在拨号" << endl; } 37 void sendMsg() { cout << "小米" << "在发短信" << endl; } 38 void hang() { cout << "小米" << "在关断电话" << endl; } 39 void recvMsg() { cout << "小米" << "在收短信" << endl; } 40 void accept(CellPhoneVisitor* p) { 41 p->visit(this); 42 } 43 }; 44 45 class HuaWei :public CellPhone { 46 public: 47 void dial() { cout << "HuaWei" << "在拨号" << endl; } 48 void sendMsg() { cout << "HuaWei" << "在发短信" << endl; } 49 void hang() { cout << "HuaWei" << "在关断电话" << endl; } 50 void recvMsg() { cout << "HuaWei" << "在收短信" << endl; } 51 void accept(CellPhoneVisitor* p) { 52 p->visit(this); 53 } 54 }; 55 56 class Oppo :public CellPhone { 57 public: 58 void dial() { cout << "Oppo" << "在拨号" << endl; } 59 void sendMsg() { cout << "Oppo" << "在发短信" << endl; } 60 void hang() { cout << "Oppo" << "在关断电话" << endl; } 61 void recvMsg() { cout << "Oppo" << "在收短信" << endl; } 62 void accept(CellPhoneVisitor* p) { 63 p->visit(this); 64 } 65 }; 66 67 class SolarisConfigure : public CellPhoneVisitor { 68 public: 69 void visit(XiaoMi *p) { 70 p->dial(); 71 p->hang(); 72 p->sendMsg(); 73 p->recvMsg(); 74 } 75 76 void visit(HuaWei *p) { 77 p->dial(); 78 p->hang(); 79 p->sendMsg(); 80 p->recvMsg(); 81 } 82 void visit(Oppo *p) { 83 p->dial(); 84 p->hang(); 85 p->sendMsg(); 86 p->recvMsg(); 87 } 88 }; 89 90 int main(void) { 91 CellPhoneVisitor* pVisitor = new SolarisConfigure; 92 XiaoMi* pXiaoMi = new XiaoMi; 93 HuaWei* pHuaWei = new HuaWei; 94 Oppo* pOppo = new Oppo; 95 cout << "将Solairs环境配置给XiaoMi" << endl; 96 pXiaoMi->accept(pVisitor); 97 cout << "将Solairs环境配置给HuaWei" << endl; 98 pHuaWei->accept(pVisitor); 99 cout << "将Solairs环境配置给Oppo" << endl; 100 pOppo->accept(pVisitor); 101 system("pause"); 102 return 0; 103 }