不破坏类封装的前提下,添加新的操作
你中有我,我中有你么?
Visitor.h
#ifndef _VISITOR_H
#define _VISITOR_H
#include <iostream>
using namespace std;
class Element;
class Visitor
{
public:
virtual ~Visitor() {
}
virtual void VisitConcreteElementA(Element* element)=0;
virtual void VisitConcreteElementB(Element* element)=0;
protected:
Visitor() {
}
};
class Element
{
public:
virtual ~Element() {
}
virtual void Accept(Visitor* vis)=0;
protected:
Element() {
}
};
class ConcreteElementA : public Element
{
public:
ConcreteElementA() {
}
~ConcreteElementA() {
}
void Accept(Visitor* vis) {
cout << "ConcreteElementA" << endl;
vis->VisitConcreteElementA(this);
}
};
class ConcreteElementB : public Element
{
public:
ConcreteElementB() {
}
~ConcreteElementB() {
}
void Accept(Visitor* vis) {
cout << "ConcreteElementB" << endl;
vis->VisitConcreteElementB(this);
}
};
class ConcreteVisitorA : public Visitor
{
public:
ConcreteVisitorA() {
}
~ConcreteVisitorA() {
}
void VisitConcreteElementA(Element* element) {
cout << "VisitConcreteElementA:A" << endl;
}
void VisitConcreteElementB(Element* element) {
cout << "VisitConcreteElementA:B" << endl;
}
};
class ConcreteVisitorB : public Visitor
{
public:
ConcreteVisitorB() {
}
~ConcreteVisitorB() {
}
void VisitConcreteElementA(Element* element) {
cout << "VisitConcreteElementB:A" << endl;
}
void VisitConcreteElementB(Element* element) {
cout << "VisitConcreteElementB:B" << endl;
}
};
#endif // _VISITOR_H
Visitor.cpp
#include "Visitor.h"
int main()
{
Visitor* vis = new ConcreteVisitorA();
Element* element = new ConcreteElementA();
element->Accept(vis);
return 0;
}
编译:make Visitor