#include <iostream>
using namespace std;
class Element;
class ElementA;
class ElementB;
#define USE_LOKI
#ifndef USE_LOKI
// class Visitor
class Visitor
{
public:
virtual void VisitElementA(ElementA&) = 0 ;
virtual void VisitElementB(ElementB&) = 0 ;
} ;
// class Visitor1
class Visitor1 : public Visitor
{
public:
virtual void VisitElementA(ElementA& pA) { cout << "Visitor1::VisitElementA" << endl; }
virtual void VisitElementB(ElementB& pB) { cout << "Visitor1::VisitElementB" << endl; }
} ;
// class Visitor2
class Visitor2 : public Visitor
{
public:
virtual void VisitElementA(ElementA& pA) { cout << "Visitor2::VisitElementA" << endl; }
virtual void VisitElementB(ElementB& pB) { cout << "Visitor2::VisitElementB" << endl; }
} ;
// class Element
class Element
{
public:
virtual void Accept(Visitor&) = 0 ;
} ;
// class ElementA
class ElementA : public Element
{
public:
virtual void Accept(Visitor& v) { v.VisitElementA(*this) ; }
} ;
// class ElementB
class ElementB : public Element
{
public:
virtual void Accept(Visitor& v) { v.VisitElementB(*this) ; }
} ;
#else
#include "Visitor.h"
using namespace Loki;
typedef CyclicVisitor<void, TYPELIST_3(Element, ElementA, ElementB)> MyVisitor;
// class Visitor1
class Visitor1 : public MyVisitor
{
public:
virtual void Visit(Element&) {}
virtual void Visit(ElementA& pA) { cout << "Visitor1::VisitElementA" << endl; }
virtual void Visit(ElementB& pB) { cout << "Visitor1::VisitElementB" << endl; }
} ;
// class Visitor2
class Visitor2 : public MyVisitor
{
public:
virtual void Visit(Element&) {}
virtual void Visit(ElementA& pA) { cout << "Visitor2::VisitElementA" << endl; }
virtual void Visit(ElementB& pB) { cout << "Visitor2::VisitElementB" << endl; }
} ;
// class Element
class Element
{
public:
virtual void Accept(MyVisitor&) = 0;
};
// class ElementA
class ElementA : public Element
{
public:
DEFINE_CYCLIC_VISITABLE(MyVisitor);
} ;
// class ElementB
class ElementB : public Element
{
public:
DEFINE_CYCLIC_VISITABLE(MyVisitor);
};
#endif
int main()
{
Visitor1 v1 ; //算法1
Visitor2 v2 ; //算法2
ElementA e1 ; //对象1
ElementB e2 ; //对象2
e1.Accept(v1) ; //对象1 + 算法1
e1.Accept(v2) ; //对象1 + 算法2
e2.Accept(v1) ; //对象2 + 算法1
e2.Accept(v2) ; //对象2 + 算法2
}
本文地址:http://com.8s8s.com/it/it24387.htm