面试:C++实现访问者模式

参考:深入应用C++11,访问者模式

 1 #include <iostream>
 2 
 3 
 4 
 5 class ConcreteElement1;
 6 class ConcreteElement2;
 7 
 8 class Visitor{
 9 public:
10     virtual ~Visitor(){};
11     virtual void visit(ConcreteElement1&) = 0;
12     virtual void visit(ConcreteElement2&) = 0;
13 };
14 
15 class ConcreteVisitor : public Visitor{
16 public:
17     virtual ~ConcreteVisitor(){};
18     void visit(ConcreteElement1& e){
19         std::cout << "ConcreteElement1::visit" << std::endl;
20     }
21     void visit(ConcreteElement2& e){
22         std::cout << "ConcreteElement2::visit" << std::endl;
23     }
24 };
25 
26 class Element{
27 public:
28     virtual ~Element(){};
29     virtual void accept(Visitor&) = 0;
30 };
31 
32 class ConcreteElement1 : public Element{
33 public:
34     virtual ~ConcreteElement1(){}
35     void accept(Visitor& v){
36         v.visit(*this);
37     }
38 };
39 class ConcreteElement2 : public Element{
40 public:
41     virtual ~ConcreteElement2(){};
42     void accept(Visitor& v){
43         v.visit(*this);
44     }
45 
46 };
47 
48 
49 int main(){
50     ConcreteVisitor visitor;
51     ConcreteElement1 emt1 = ConcreteElement1();
52     emt1.accept(visitor);
53     ConcreteElement2 emt2 = ConcreteElement2();
54     emt2.accept(visitor);
55     return 0;
56 }

 

posted @ 2017-08-08 10:21  wxquare  阅读(437)  评论(0编辑  收藏  举报