C++访问者模式(Visitor)

 C++
时间:

应用场景

1、对象结构中对象对应的类很少改变,但经常需要在此对象结构上定义新的操作。

2、需要对一个对象结构中的对象进行很多不同的并且不相关的操作,而需要避免让这些操作”污染”这些对象的类,也不希望在增加新操作时修改这些类。

Visitor

  • Element.h
#pragma cone

class Visitor;

class Element
{
    public:
        virtual ~Element() {}
        virtual void Accept(Visitor* vis) = 0;
    protected:
        Element() {}
    private:
};

class ConcreteElementA : public Element
{
    public:
        ConcreteElementA() {}
        ~ConcreteElementA() {}
        void Accept(Visitor* vis);
    protected:
    private:
};

class ConcreteElementB : public Element
{
    public:
        ConcreteElementB() {}
        ~ConcreteElementB() {}
        void Accept(Visitor* vis);
    protected:
    private:
};
  • Element.cpp
#include"Element.h"
#include"Visitor.h"
#include<iostream>
using namespace std;

void ConcreteElementA::Accept(Visitor* vis)
{
    vis->VisitConcreteElementA(this);
    cout << "Visiting ConcreteElementA..." << endl;
}

void ConcreteElementB::Accept(Visitor* vis)
{
    vis->VisitConcreteElementB(this);
    cout << "Visiting ConcreteElementB..." << endl;
}
  • Visitor.h
#pragma cone

class ConcreteElementA;

class ConcreteElementB;

class Element;

class Visitor
{
    public:
        virtual ~Visitor() {}
        virtual void VisitConcreteElementA(Element* elm) = 0;
        virtual void VisitConcreteElementB(Element* elm) = 0;
    protected:
        Visitor() {}
    private:
};

class ConcreteVisitorA : public Visitor
{
    public:
        ConcreteVisitorA() {}
        ~ConcreteVisitorA() {}
        void VisitConcreteElementA(Element* elm);
        void VisitConcreteElementB(Element* elm);
    protected:
    private:
};

class ConcreteVisitorB : public Visitor
{
    public:
        ConcreteVisitorB() {}
        ~ConcreteVisitorB() {}
        void VisitConcreteElementA(Element* elm);
        void VisitConcreteElementB(Element* elm);
    protected:
    private:
};
  • Visitor.cpp
#include"Visitor.h"

#include"Element.h"

#include<iostream>

using namespace std;

void ConcreteVisitorA::VisitConcreteElementA(Element* elm)
{
    cout << "i will visit ConcreteElementA..." << endl;
}   

void ConcreteVisitorA::VisitConcreteElementB(Element* elm)
{
    cout << "i will visit ConcreteElementB..." << endl;
}

void ConcreteVisitorB::VisitConcreteElementA(Element* elm)
{
    cout << "i will visit ConcreteElementA..." << endl;
}

void ConcreteVisitorB::VisitConcreteElementB(Element* elm)
{
    cout << "i will visit ConcreteElementB..." << endl;
}
  • main.cpp
#include<iostream>
#include"Element.h"
#include"Visitor.h"
using namespace std;

int main(int argc, char* argv[])
{
    Visitor* vis = new ConcreteVisitorA();
    Element* elm = new ConcreteElementA();
    elm->Accept(vis);
    return 0;
}

0 评论