码迷,mamicode.com
首页 > 其他好文 > 详细

Visitor

时间:2014-12-18 18:18:30      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   ar   io   color   os   sp   for   

#include <iostream>
#include <vector>

using namespace std;


#define DESTROY_POINTER(ptr) if (ptr) { delete ptr; ptr = NULL; }


class Element;


class Visitor
{
public:
    virtual void Visit(Element* pElement)=0;
};

class ConcreteVisitorA : public Visitor
{
public:
    void Visit(Element* pElement);
};

class ConcreteVisitorB : public Visitor
{
public:
    void Visit(Element* pElement);
};

class Element
{
public:
    virtual void Accept(Visitor* pVisitor)=0;
    virtual void Interface1()=0;
    virtual void Interface2()=0;
};

class ConcreteElementA : public Element
{
public:
    void Accept(Visitor* pVisitor)
    {
        pVisitor->Visit(this);
    }
    void Interface1() { cout<<"ConcreteElementA::Interface1"<<endl; }
    void Interface2() { cout<<"ConcreteElementA::Interface2"<<endl; }
};

class ConcreteElementB : public Element
{
public:
    void Accept(Visitor* pVisitor)
    {
        pVisitor->Visit(this);
    }
    void Interface1() { cout<<"ConcreteElementB::Interface1"<<endl; }
    void Interface2() { cout<<"ConcreteElementB::Interface2"<<endl; }
};

void ConcreteVisitorA::Visit(Element* pElement)
{
    pElement->Interface1();
}

void ConcreteVisitorB::Visit(Element* pElement)
{
    pElement->Interface2();
}

class Structure
{
public:
    virtual ~Structure()
    {
        for (unsigned int i = 0; i < m_elementList.size(); i++)
        {
            delete m_elementList[i];
        }
        m_elementList.clear();
    }

    void Accept(Visitor* pVisitor)
    {
        for (unsigned int i = 0; i < m_elementList.size(); i++)
        {
            m_elementList[i]->Accept(pVisitor);
        }
    }
    
    void AddElement(Element* pElement)
    {
        m_elementList.push_back(pElement);
    }
private:
    vector<Element*> m_elementList;
};



int main(int argc, char *argv[])
{
    Structure structure;

    structure.AddElement(new ConcreteElementA);
    structure.AddElement(new ConcreteElementB);

    Visitor* pVisitorA = new ConcreteVisitorA;
    Visitor* pVisitorB = new ConcreteVisitorB;
    
    structure.Accept(pVisitorA);
    structure.Accept(pVisitorB);

    DESTROY_POINTER(pVisitorA);
    DESTROY_POINTER(pVisitorB);

    return 0;
}

 

Visitor

标签:des   style   blog   ar   io   color   os   sp   for   

原文地址:http://www.cnblogs.com/stanley198610281217/p/4172131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!