表示一个作用于某对象结构中的各元素的操作。使得可以在不改变(稳定)各元素的类的前提下定义(扩展)作用于这些元素的新操作(变化)。
#include<iostream> using namespace std; class Visitor; class Element { public: virtual void accept(Visitor& visitor) = 0;//第一次多态辨析(找accept) virtual ~Element() {} }; class ElementA :public Element { public: virtual void accept(Visitor& visitor) override; //第二次多态辨析(找visitElementA) }; class ElementB :public Element { public: void accept(Visitor& visitor) override; }; class Visitor { public: virtual void visitElementA(ElementA& element) = 0; virtual void visitElementB(ElementB& element) = 0; virtual ~Visitor() {} }; void ElementA::accept(Visitor& visitor) { visitor.visitElementA(*this);//第二次多态辨析(找visitElementA) } void ElementB::accept(Visitor& visitor) { visitor.visitElementB(*this); } //================= //对行为进行更改 class Visiter1 :public Visitor { public: void visitElementA(ElementA& element) override { cout << "Visitor1 process ElementA" << endl; } void visitElementB(ElementB& element) override { cout << "Visitor1 process ElementB" << endl; } }; class Visiter2 :public Visitor { public: void visitElementA(ElementA& element) override { cout << "Visitor2 process ElementA" << endl; } void visitElementB(ElementB& element) override { cout << "Visitor2 process ElementB" << endl; } }; int main() { Visiter1 visitor; ElementA elementA; elementA.accept(visitor);//二次多态辨析 ElementB elementB; elementB.accept(visitor); return 0; }