设计模式-Visitor(行为模式) 一个类在不修改自己的同时增加了新的操作,存在问题是 1:破坏了封装性 2:扩展困难
//以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//Visitor.h
#pragma once class ConcreateElementA; class ConcreateElementB; class Element; class Visitor { public: virtual ~Visitor(); virtual void VisitConcreateElementA(Element* elm) = 0; virtual void VisitConcreateElementB(Element* elm) = 0; protected: Visitor(); private: }; class ConcreateVisitorA :public Visitor { public: ConcreateVisitorA(); virtual ~ConcreateVisitorA(); virtual void VisitConcreateElementA(Element* elm); virtual void VisitConcreateElementB(Element* elm); protected: private: }; class ConcreateVisitorB :public Visitor { public: ConcreateVisitorB(); virtual ~ConcreateVisitorB(); virtual void VisitConcreateElementA(Element* elm); virtual void VisitConcreateElementB(Element* elm); protected: private: };
//Element.h
#pragma once class Visitor; class Element { public: virtual ~Element(); virtual void Accept(Visitor* vis) = 0; protected: Element(); private: }; class ConcreateElementA :public Element { public: ConcreateElementA(); ~ConcreateElementA(); void Accept(Visitor* vis); protected: private: }; class ConcreateElementB :public Element { public: ConcreateElementB(); ~ConcreateElementB(); void Accept(Visitor* vis); protected: private: };
//Visitor.cpp
#include"Element.h" #include"Visitor.h" #include<iostream> Visitor::Visitor(){} Visitor::~Visitor(){} ConcreateVisitorA::ConcreateVisitorA(){} ConcreateVisitorA::~ConcreateVisitorA(){} void ConcreateVisitorA::VisitConcreateElementA(Element* elm) { std::cout << "i will visit concreateElementA ... " << std::endl; } void ConcreateVisitorA::VisitConcreateElementB(Element* elm) { std::cout << "i will visit concreateElementB ..." << std::endl; } ConcreateVisitorB::ConcreateVisitorB(){} ConcreateVisitorB::~ConcreateVisitorB(){} void ConcreateVisitorB::VisitConcreateElementA(Element* elm) { std::cout << "i will visit ConcreateElementA ..." << std::endl; } void ConcreateVisitorB::VisitConcreateElementB(Element* elm) { std::cout << "i will visit ConcreateElementB ..." << std::endl; }
//Element.cpp
#include "Element.h" #include "Visitor.h" #include<iostream> Element::Element(){} Element::~Element(){} void Element::Accept(Visitor* vis){} ConcreateElementA::ConcreateElementA(){} ConcreateElementA::~ConcreateElementA(){} void ConcreateElementA::Accept(Visitor* vis) { vis->VisitConcreateElementA(this); std::cout << "Visitting ConcreateElementA ... " << std::endl; } ConcreateElementB::ConcreateElementB(){} ConcreateElementB::~ConcreateElementB(){} void ConcreateElementB::Accept(Visitor* vis) { vis->VisitConcreateElementB(this); std::cout << "Visitting ConcreateElementB ... " << std::endl; }
//main.cpp
#include"Element.h" #include"Visitor.h" #include<string> int main(int args, char* argv) { Visitor* vis = new ConcreateVisitorA(); Element* elm = new ConcreateElementA(); elm->Accept(vis); getchar(); return 0; }