设计模式-Iterator(行为模式) 将聚合的遍历封装到一个类中
Posted fourmi_gsj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式-Iterator(行为模式) 将聚合的遍历封装到一个类中相关的知识,希望对你有一定的参考价值。
//以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//Aggregate.h
#pragma once class Iterator; typedef int Object; class Interator; class Aggregate { public: virtual ~Aggregate(); virtual Iterator* CreateIterator() = 0; virtual Object GetItem(int idx) = 0; virtual int GetSize() = 0; protected: Aggregate(); private: }; class ConcreteAggregate :public Aggregate { public: enum { SIZE=3 }; ConcreteAggregate(); ~ConcreteAggregate(); Iterator* CreateIterator(); Object GetItem(int idx); int GetSize(); protected: private: Object _objs[SIZE]; };
//Aggregate.cpp
#include"Aggregate.h" #include"Iterator.h" #include<iostream> Aggregate::Aggregate(){} Aggregate::~Aggregate(){} ConcreteAggregate::ConcreteAggregate() { for (int i = 0; i < SIZE; ++i) { _objs[i] = i; } } ConcreteAggregate::~ConcreteAggregate(){} Iterator* ConcreteAggregate::CreateIterator() { return new ConcreateIterator(this); } Object ConcreteAggregate::GetItem(int idx) { if (idx < this->GetSize())return _objs[idx]; else return -1; } int ConcreteAggregate::GetSize() { return SIZE; }
//Iterator.h
#pragma once class Aggregate; typedef int Object; class Iterator { public: virtual ~Iterator(); virtual void First() = 0; virtual void Next() = 0; virtual bool IsDone() = 0; virtual Object CurrentItem() = 0; protected: Iterator(); private: }; class ConcreateIterator :public Iterator { public: ConcreateIterator(Aggregate* ag, int idx = 0); ~ConcreateIterator(); void First(); void Next(); bool IsDone(); Object CurrentItem(); protected: private: Aggregate* _ag; int _idx; };
//Iterator.cpp
#include"Iterator.h" #include"Aggregate.h" Iterator::Iterator() { } Iterator::~Iterator() { } ConcreateIterator::ConcreateIterator(Aggregate* ag, int idx) { this->_ag = ag; this->_idx = idx; } ConcreateIterator::~ConcreateIterator(){} Object ConcreateIterator::CurrentItem() { return _ag->GetItem(_idx); } void ConcreateIterator::Next() { if (_idx < _ag->GetSize())++_idx; } bool ConcreateIterator::IsDone() { return (_idx == _ag->GetSize()); } void ConcreateIterator::First() { _idx = 0; }
//main.cpp
#include"Aggregate.h" #include"Iterator.h" #include<string> #include<iostream> int main(int args, char* argv) { Aggregate* ag = new ConcreteAggregate(); Iterator* it = new ConcreateIterator(ag); for (; !(it->IsDone()); ++it) std::cout << it->CurrentItem() << std::endl; getchar(); return 0; }
以上是关于设计模式-Iterator(行为模式) 将聚合的遍历封装到一个类中的主要内容,如果未能解决你的问题,请参考以下文章