访问者模式中,有一个数据体,添加了各个访问对象。这些访问对象在不同的状态时,会有不同的反应。这种模式中,对象与状态相分离,互不干扰。
Visitor.h内容
1 #ifndef Visitor_H_H 2 #define Visitor_H_H 3 4 5 #include <iostream> 6 #include <vector> 7 using namespace std; 8 9 class State 10 { 11 public: 12 virtual void getManState() = 0; 13 virtual void getWomanState() = 0; 14 virtual ~State() {} 15 16 }; 17 18 class StateHappy : public State 19 { 20 public: 21 virtual void getManState(){ 22 cout << "Man drinks when happy!" << endl; 23 } 24 virtual void getWomanState(){ 25 cout << "Woman go shopping when happy!" << endl; 26 } 27 }; 28 29 30 class StateSad : public State 31 { 32 public: 33 virtual void getManState(){ 34 cout << "Man smokes when sad!" << endl; 35 } 36 virtual void getWomanState(){ 37 cout << "Woman weeps when sad!" << endl; 38 } 39 40 }; 41 42 43 class People 44 { 45 public: 46 virtual void visit(State *state) = 0; 47 virtual ~People() {} 48 }; 49 50 class Man : public People 51 { 52 public: 53 virtual void visit(State *state){ 54 state->getManState(); 55 } 56 }; 57 58 class Woman : public People 59 { 60 public: 61 virtual void visit(State *state){ 62 state->getWomanState(); 63 } 64 }; 65 66 67 class Visitor 68 { 69 public: 70 Visitor() : state(NULL) {} 71 void visit(){ 72 for(size_t i=0; i<vecPeople.size(); ++i){ 73 vecPeople[i]->visit(state); 74 } 75 } 76 77 void addItem(People *people){ 78 vecPeople.push_back(people); 79 } 80 81 void setState(State *state0) { state = state0; } 82 83 private: 84 vector<People*> vecPeople; 85 State *state; 86 }; 87 88 89 void VisitorTest() 90 { 91 Visitor *visitor = new Visitor(); 92 visitor->addItem(new Man()); 93 visitor->addItem(new Woman()); 94 95 State *state1 = new StateHappy(); 96 State *state2 = new StateSad(); 97 98 visitor->setState(state1); 99 visitor->visit(); 100 101 visitor->setState(state2); 102 visitor->visit(); 103 104 delete visitor; 105 } 106 107 #endif
运行结果:
实例中,男士和女士在高兴和悲伤时会有不同的动作反应,由一个visitor添加所有People的实例后,设置不同的状态以对每个个体进行访问。
时间: 2024-11-05 17:28:08