标签:style blog http color os io ar art div
【1】什么是访问者模式?
访问者模式:
【2】访问者模式代码示例:
代码示例1:
1 #include <iostream> 2 #include <list> 3 #include <string> 4 using namespace std; 5 6 class Person 7 { 8 public: 9 string action; 10 virtual void getConclusion() = 0; 11 }; 12 13 class Man:public Person 14 { 15 public: 16 void getConclusion() 17 { 18 if (action == "成功") 19 { 20 cout << "男人成功时,背后多半有一个伟大的女人。" << endl; 21 } 22 else if (action == "恋爱") 23 { 24 cout << "男人恋爱时,凡事不懂装懂。" << endl; 25 } 26 } 27 }; 28 29 class Woman : public Person 30 { 31 public: 32 void getConclusion() 33 { 34 if (action == "成功") 35 { 36 cout << "女人成功时,背后多半有失败的男人。" << endl; 37 } 38 else if (action == "恋爱") 39 { 40 cout << "男人恋爱时,遇到事懂也装不懂。" << endl; 41 } 42 } 43 }; 44 45 int main() 46 { 47 list<Person*> persons; 48 49 Person *man1 = new Man(); 50 man1->action = "成功"; 51 persons.push_back(man1); 52 53 Person *woman1 = new Woman(); 54 woman1->action = "成功"; 55 persons.push_back(woman1); 56 57 Person *man2 = new Man(); 58 man2->action = "恋爱"; 59 persons.push_back(man2); 60 61 Person *woman2 = new Woman(); 62 woman2->action = "恋爱"; 63 persons.push_back(woman2); 64 65 list<Person*>::iterator iter = persons.begin(); 66 while (iter != persons.end()) 67 { 68 (*iter)->getConclusion(); 69 ++iter; 70 } 71 return 0; 72 } 73 //Result: 74 /* 75 男人成功时,背后多半有一个伟大的女人。 76 女人成功时,背后多半有失败的男人。 77 男人恋爱时,凡事不懂装懂。 78 男人恋爱时,遇到事懂也装不懂。 79 */
代码示例2:
Good Good Study, Day Day Up.
顺序 选择 循环 总结
标签:style blog http color os io ar art div
原文地址:http://www.cnblogs.com/Braveliu/p/3957007.html