设计模式-行为-访问者
原创
©著作权归作者所有:来自51CTO博客作者shixin_0125的原创作品,请联系作者获取转载授权,否则将追究法律责任
#pragma once
#ifndef VISITOR_H
#define VISITOR_H
class Visitor;
class Element
{
public:
virtual ~Element(){}
virtual void Accept(Visitor &rVisitor) = 0;
protected:
Element(){}
};
class ConcreateElementA : public Element
{
public:
virtual ~ConcreateElementA() {}
virtual void Accept(Visitor &rVisitor);
};
class ConcreateElementB : public Element
{
public:
virtual ~ConcreateElementB() {}
virtual void Accept(Visitor &rVisitor);
};
class Visitor
{
public:
virtual ~Visitor(){}
virtual void VisitConcreateElementA(ConcreateElementA *pConcreateElementA) = 0;
virtual void VisitConcreateElementB(ConcreateElementB *pConcreateElementB) = 0;
protected:
Visitor(){}
};
class ConcreateVisitorA : public Visitor
{
public:
virtual ~ConcreateVisitorA(){}
virtual void VisitConcreateElementA(ConcreateElementA *pConcreateElementA);
virtual void VisitConcreateElementB(ConcreateElementB *pConcreateElementB);
};
class ConcreateVisitorB : public Visitor
{
public:
virtual ~ConcreateVisitorB(){}
virtual void VisitConcreateElementA(ConcreateElementA *pConcreateElementA);
virtual void VisitConcreateElementB(ConcreateElementB *pConcreateElementB);
};
#endif
#include "StdAfx.h"
#include "visitor_impl.h"
#include <iostream>
void ConcreateElementA::Accept(Visitor &rVisitor)
{
rVisitor.VisitConcreateElementA(this);
}
void ConcreateElementB::Accept(Visitor &rVisitor)
{
rVisitor.VisitConcreateElementB(this);
}
void ConcreateVisitorA::VisitConcreateElementA(ConcreateElementA *pConcreateElementA)
{
std::cout << "VisitConcreateElementA By ConcreateVisitorA\n";
}
void ConcreateVisitorA::VisitConcreateElementB(ConcreateElementB *pConcreateElementA)
{
std::cout << "VisitConcreateElementB By ConcreateVisitorA\n";
}
void ConcreateVisitorB::VisitConcreateElementA(ConcreateElementA *pConcreateElementA)
{
std::cout << "VisitConcreateElementA By ConcreateVisitorB\n";
}
void ConcreateVisitorB::VisitConcreateElementB(ConcreateElementB *pConcreateElementA)
{
std::cout << "VisitConcreateElementB By ConcreateVisitorB\n";
}
#include "stdafx.h"
#include "visitor_impl.h"
#include <stdlib.h>
int _tmain(int argc, _TCHAR* argv[])
{
Visitor *pVisitor1 = new ConcreateVisitorA();
Visitor *pVisitor2 = new ConcreateVisitorB();
Element *pElementA = new ConcreateElementA();
pElementA->Accept(*pVisitor1);
pElementA->Accept(*pVisitor2);
Element *pElementB = new ConcreateElementB();
pElementB->Accept(*pVisitor1);
pElementB->Accept(*pVisitor2);
delete pElementA;
delete pElementB;
delete pVisitor1;
delete pVisitor2;
system("pause");
return 0;
}