设计模式 - Visitor
意图:表示一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
class Visitor; class Element { public: Element() {} virtual ~Element() {} virtual void Accept(Visitor* visitor) = 0; }; class Visitor { public: Visitor() {} virtual ~Visitor() {} virtual void VisitElementA(Element* element) = 0; virtual void VisitElementB(Element* element) = 0; }; class ConcreteElementA: public Element { public: ConcreteElementA() {} ~ConcreteElementA() {} void Accept(Visitor* visitor) { visitor->VisitElementA(this); } }; class ConcreteElementB: public Element { public: ConcreteElementB() {} ~ConcreteElementB() {} void Accept(Visitor* visitor) { visitor->VisitElementB(this); } }; class ConcreteVisitorA: public Visitor { public: ConcreteVisitorA() {} ~ConcreteVisitorA() {} void VisitElementA(Element* element) { cout<<"ConcreteVisitorA::VisitElementA()"<<endl; } void VisitElementB(Element* element) { cout<<"ConcreteVisitorA::VisitElementB()"<<endl; } }; class ConcreteVisitorB: public Visitor { public: ConcreteVisitorB() {} ~ConcreteVisitorB() {} void VisitElementA(Element* element) { cout<<"ConcreteVisitorB::VisitElementA()"<<endl; } void VisitElementB(Element* element) { cout<<"ConcreteVisitorB::VisitElementB()"<<endl; } };