访问者模式可以将算法与其操作的对象类进行解耦。这种模式通过构建一个新的Visitor类,以防止新功能被整合进已有的类中(至少以更小的代价被整合进已有类中)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 class Shape { public : virtual void move (int x, int y) = 0 ; virtual void draw () = 0 ; virtual void accept (Visitor* v) = 0 ; virtual ~Shape () {} }; class Dot : public Shape { void accept (Visitor* v) override { v->visitDot (this ); } }; class Circle : public Shape { void accept (Visitor* v) override { v->visitCircle (this ); } }; class Rectangle : public Shape { void accept (Visitor* v) override { v->visitRectangle (this ); } }; class CompoundShape : public Shape { void accept (Visitor* v) override { v->visitCompoundShape (this ); } }; class Visitor { public : virtual std::string visitDot (Dot* d) = 0 ; virtual std::string visitCircle (Circle* c) = 0 ; virtual std::string visitRectangle (Rectangle* r) = 0 ; virtual std::string visitCompoundShape (CompoundShape* cs) = 0 ; } class XMLExportVisitor : public Visitor { std::string visitDot (Dot* d) override { } std::string visitCircle (Circle* c) override { } }; int main (int argc, char * argv[]) { std::vector<Shape*> shapes; XMLExportVisitor exportVisitor = new XMLExportVisitor (); for (Shape* s: shapes) { s->accept (exportVisitor); } delete exportVisitor; return 0 ; }