C++设计模式Visitor+Iterator简单实现

2014-11-23 22:19:35 · 作者: · 浏览: 4
#include
#include
#include
class ElementA;
class CompositeElement;
template
class MyList;
template
class MyListIterator;
template
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 MyListIterator{
    public:
        MyListIterator(const MyList* aList);
        virtual void First();
        virtual void Next();
        virtual bool IsDone() const;
        virtual T CurrentItem() const;
    private:
        const MyList* _list;
        long _current;
};


template
MyListIterator::MyListIterator(const MyList *aList):_list(aList), _current(0){
}


template
void MyListIterator::First(){
    _current = 0;
}


template
void MyListIterator::Next(){
    _current ++;
}


template
bool MyListIterator::IsDone() const{
    return _current >= _list->size();
}


template
T MyListIterator::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
* list):_children(list){} virtual void Accept(Visitor& v); private: MyList* _children; }; void CompositeElement::Accept(Visitor& v){ MyListIterator 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 *list = new MyList; list->push_back(newa); list->push_back(newb); CompositeElement* aptr = new CompositeElement(list); PrintVisitor printptr; aptr->Accept(printptr); }