访问器(visitor)模式
意图:主要将数据结构与数据操作分离。
主要解决:稳定的数据结构和易变的操作耦合问题。
代码:
#include <iostream> #include <list> using namespace std; class ComputerPartVisitor; class ComputerPart { public: virtual ~ComputerPart() {} public: virtual void accept(ComputerPartVisitor *v) = 0; }; class KeyBoard; class Mouse; class Monitor; class ComputerPartVisitor { public: virtual ~ComputerPartVisitor() {} public: virtual void visit(KeyBoard *keyboard) = 0; virtual void visit(Mouse *mouse) = 0; virtual void visit(Monitor *monitor) = 0; }; class KeyBoard : public ComputerPart { public: virtual void accept(ComputerPartVisitor *v) { v->visit(this); } }; class Mouse : public ComputerPart { public: virtual void accept(ComputerPartVisitor *v) { v->visit(this); } }; class Monitor : public ComputerPart { public: virtual void accept(ComputerPartVisitor *v) { v->visit(this); } }; class ComputerPartDisplayVisitor : public ComputerPartVisitor { public: virtual void visit(KeyBoard *keyboard) { cout << "Displaying KeyBoard." << endl; } virtual void visit(Mouse *mouse) { cout << "Displaying Mouse." << endl; } virtual void visit(Monitor *monitor) { cout << "Displaying Monitor." << endl; } }; class Computer { public: Computer() { _computerPartList.clear(); addComponent(new KeyBoard); addComponent(new Mouse); addComponent(new Monitor); } ~Computer() { for (auto it = _computerPartList.begin(); it != _computerPartList.end(); ++it) { delete *it; } _computerPartList.clear(); } public: void addComponent(ComputerPart *cp) { _computerPartList.push_back(cp); } void accept(ComputerPartVisitor *v) { for (auto it = _computerPartList.begin(); it != _computerPartList.end(); ++it) { (*it)->accept(v); } } private: list<ComputerPart*> _computerPartList; }; void test() { Computer *c = new Computer(); ComputerPartVisitor *visitor = new ComputerPartDisplayVisitor(); c->accept(visitor); delete c; delete visitor; } int main() { test(); cin.get(); return 0; }
效果: