Home > AI > Uncategorized

C++访客者模式

#include <iostream>
#include <list>
#include <string>

using namespace std;

class ParkElement;

//接口
class Visitor//不同的访问者 访问公园完成不同的动作
{
public:
    virtual void visit(ParkElement *park) = 0;
};

class ParkElement//公园不同的部分接受不同的访问者
{
public:
    char name;
    virtual void accept(Visitor *v) = 0;
};


//Parks
class ParkA : public ParkElement
{
public:
    virtual void accept(Visitor *v)
    { v->visit(this); }
};

class ParkB : public ParkElement
{
public:
    virtual void accept(Visitor *v)
    { v->visit(this); }
};

class Park : public ParkElement
{
public:
    Park()
    { m_list.clear(); }
    void setPart(ParkElement *e){
        m_list.push_back(e);}
public:
    void accept(Visitor *v)
    {
        for (list<ParkElement *>::iterator it = m_list.begin(); it != m_list.end(); it++)
        { (*it)->accept(v);}
    }
private:
    list<ParkElement *> m_list;
};


//Visitors
class VisitorA : public Visitor
{
public:
    virtual void visit(ParkElement *park)
    { cout << "清洁工A 访问 公园A 部分,打扫卫生完毕" << endl; }
};

class VisitorB : public Visitor
{
public:
    virtual void visit(ParkElement *park)
    { cout << "清洁工B 访问 公园B 部分,打扫卫生完毕" << endl; }
};

class VisitorManager : public Visitor
{
public:
    virtual void visit(ParkElement *park)
    { cout << "管理员 检查" << park->name << "卫生情况" << endl;}
};


int main()
{

    VisitorA *visitorA = new VisitorA;
    VisitorB *visitorB = new VisitorB;
    
    ParkA *parkA = new ParkA;
    ParkB *parkB = new ParkB;

    parkA->name = 'A';
    parkB->name = 'B';
    parkA->accept(visitorA);
    parkB->accept(visitorB);
    
    
    VisitorManager *visitorManager = new VisitorManager;
    Park * park = new Park;
    park->setPart(parkA);
    park->setPart(parkB);
    park->accept(visitorManager);
  
  
}

 

Related posts:

Leave a Reply