Visitor模式示例(使用Loki类库)

#include <iostream>
using namespace std;

class Element;
class ElementA;
class ElementB;

#define USE_LOKI

#ifndef USE_LOKI
    // Abstract Visitor
    class Visitor{
    public:    
        virtual void VisitElementA(ElementA&) = 0;    
        virtual void VisitElementB(ElementB&) = 0;
    };
    // Concrete Visitors
    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 : public Visitor{
    public:    
        virtual void VisitElementA(ElementA& pA) { cout << "Visitor2::VisitElementA" << endl; }    
        virtual void VisitElementB(ElementB& pB) { cout << "Visitor2::VisitElementB" << endl; }
    };
    // Abstract Element
    class Element{
    public:    
        virtual void Accept(Visitor&) = 0 ;
    };
    // Concrete Elements A and B
    class ElementA : public Element{
    public:
        virtual void Accept(Visitor& v) { v.VisitElementA(*this); }
    };
    class ElementB : public Element{
    public:    
        virtual void Accept(Visitor& v) { v.VisitElementB(*this); }
    };
#else
    #include "Visitor.h"
    using namespace Loki;
    // Abstract Visitor
    typedef CyclicVisitor<void, TYPELIST_3(Element, ElementA, ElementB)> MyVisitor;
    // Concrete Visitors
    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 : 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; }
    };
    // Abstract Element
    class Element{
    public:    
        virtual void Accept(MyVisitor&) = 0;
    };
    // Concrete Elements A and B
    class ElementA : public Element{
    public:    
        DEFINE_CYCLIC_VISITABLE(MyVisitor);
    };
    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
}

你可能感兴趣的:(Visitor模式示例(使用Loki类库))