Visitor模式在不破坏类的前提下,为类提供增加新的新操作。
Visitor模式经常用于将更新的设计封装在一个类中,并且由待更改的类提供一个接受接口,其关键技术在于双分派技术,Element类提供接口,通过Accept实现具体使用哪一个具体的Visit操作;
当然如果有很多的修改,便可以提供更多的Element的Visitor,但是会破坏系统的封装,并且难于扩展。
C++设计模式原书中的代码:
#include <iostream>
using namespace std;
class Element;
class Visitor
{
public:
virtual ~Visitor(){}
virtual void visitConElemA(Element* elm)=0;
virtual void visitConElemB(Element* elm)=0;
protected:
Visitor(){}
};
class ConcreteVisitorA:public Visitor
{
public:
ConcreteVisitorA(){};
virtual ~ConcreteVisitorA(){};
void visitConElemA(Element* elm){cout<<"visit A";}
void visitConElemB(Element* elm){cout<<"visit B";}
};
class ConcreteVisitorB:public Visitor
{
public:
ConcreteVisitorB(){};
virtual ~ConcreteVisitorB(){};
void visitConElemA(Element* elm){cout<<"visit A";}
void visitConElemB(Element* elm){cout<<"visit B";}
};
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<<"This is A interface "<<endl;
vis->visitConElemA(this);
}
};
class ConcreteElementB:public Element
{
public:
ConcreteElementB(){}
~ConcreteElementB(){}
void Accept(Visitor* vis)
{
cout<<"This is B interface ";
vis->visitConElemB(this);
}
};
void main()
{
Visitor* vis=new ConcreteVisitorA();
Element* elm=new ConcreteElementA();
elm->Accept(vis);
delete elm;
delete vis;
}