Visitor模式在不破壞類的前提下,為類提供增加新的新操作。
Visitor模式經常用於將更新的設計封裝在一個類中,並且由待更改的類提供一個接受接口,其關鍵技術在於雙分派技術,Element類提供接口,通過Accept實現具體使用哪一個具體的Visit操作;
#includeusing 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 "< 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; }