C++设计模式Visitor+Iterator简单实现
#include<stdio.h>#include<string.h>#include<ctype.h>class ElementA;class CompositeElement;template<class T>class MyList;template<class T>class MyListIterator;template<class T>class MyList{ public: MyList():m_size_(0), m_member_(new T*[1024]){ } long size() const{ return m_size_; } void push_back(T elem){ m_member_[(++m_size_) - 1] = new T(elem); } T &Get(long index) const{ return *m_member_[index]; } private: long m_size_; T **m_member_;};template<class T>class MyListIterator{ public: MyListIterator(const MyList<T>* aList); virtual void First(); virtual void Next(); virtual bool IsDone() const; virtual T CurrentItem() const; private: const MyList<T>* _list; long _current;};template<class T>MyListIterator<T>::MyListIterator(const MyList<T> *aList):_list(aList), _current(0){}template<class T>void MyListIterator<T>::First(){ _current = 0;}template<class T>void MyListIterator<T>::Next(){ _current ++;}template<class T>bool MyListIterator<T>::IsDone() const{ return _current >= _list->size();}template<class T>T MyListIterator<T>::CurrentItem() const{ if(IsDone()){ throw 20; } return _list->Get(_current);}const static long DEFAULT_SIZE = 10;class Visitor{ public: virtual void VisitElementA(ElementA*){} virtual void VisitCompositeElement(CompositeElement*){} protected: Visitor(){ }};class Element{ public: virtual ~Element(){ } virtual void Accept(Visitor&) = 0; protected: Element(){ }};class ElementA : public Element{ public: ElementA(char* name):m_name_(name){ } virtual void Accept(Visitor& v){ v.VisitElementA(this); } char* getName() const{ return m_name_; } void changeCase(){ for(int i=0; i<strlen(m_name_); i++){ m_name_[i] = toupper(m_name_[i]); } } private: char *m_name_;};class CompositeElement : public Element { public: CompositeElement(MyList<Element*>* list):_children(list){} virtual void Accept(Visitor& v); private: MyList<Element *>* _children;};void CompositeElement::Accept(Visitor& v){ MyListIterator<Element*> iter(_children); for(iter.First(); !iter.IsDone(); iter.Next()) { iter.CurrentItem()->Accept(v); } v.VisitCompositeElement(this);}class PrintVisitor : public Visitor{ public: virtual void VisitElementA(ElementA* elem){ printf("%s\n",elem->getName()); }};class UpperCaseVisitor : public Visitor{ public: virtual void VisitElementA(ElementA* elem){ elem->changeCase(); }};int main(){ char *str = new char[128]; char *str2 = new char[128]; strcpy(str,"owen"); strcpy(str2,"GBS"); ElementA *newa = new ElementA(str); ElementA *newb = new ElementA(str2); MyList<Element*> *list = new MyList<Element*>; list->push_back(newa); list->push_back(newb); CompositeElement* aptr = new CompositeElement(list); PrintVisitor printptr; aptr->Accept(printptr);}