访问者模式:
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.(封装一些作用于某种数据结构中的各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。)
C++代码实现
#include <iostream>
using namespace std;
class ConcreateElement;
class Visitor {
public:
virtual void VisitConcreateElement(ConcreateElement* pConcreateElement) = 0;
};
class ConcreateVisitor : public Visitor {
public:
void VisitConcreateElement(ConcreateElement* pConcreateElement) {
cout << "visit ConcreateElement" << endl;
}
};
class Element {
public:
virtual void Accept(Visitor* pVisitor) = 0;
};
class ConcreateElement : public Element {
public:
void Accept(Visitor* pVisitor) {
pVisitor->VisitConcreateElement(this);
DoSomething();
}
void DoSomething() {
cout << "ConcreateElement DoSomething" << endl;
}
};
#include "Visitor.h"
int main()
{
Element* pElement = new ConcreateElement();
ConcreateVisitor* pConcreateVisitor = new ConcreateVisitor();
pElement->Accept(pConcreateVisitor);
delete pConcreateVisitor;
delete pElement;
return 0;
}
考虑使用访问者模式的情况:业务规则要求遍历多个不同的对象。
迭代器模式只能访问同类或同接口的数据。而访问者模式是对迭代器模式的扩充,可以遍历不同的对象,然后执行不同的操作,也就是针对访问的对象不同,执行不同的操作。
访问者模式还有一个用途,就是充当拦截器(Interceptor)