标签:style blog io color os 使用 sp on div
Visitor模式在不破坏类的前提下,为类提供增加新的新操作。
Visitor模式经常用于将更新的设计封装在一个类中,并且由待更改的类提供一个接受接口,其关键技术在于双分派技术,Element类提供接口,通过Accept实现具体使用哪一个具体的Visit操作;
#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; }
标签:style blog io color os 使用 sp on div
原文地址:http://blog.csdn.net/yc7369/article/details/41812559