首页 > 代码库 > 访问器模式
访问器模式
访问器(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; }
效果:
访问器模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。