标签:style blog http color strong os
定义
template<class Item>
class AbstractList {
public:
virtual Iterator* createIterator() const = 0;
virtual int count() const = 0;
virtual void append(Item item) = 0;
virtual void remove(Item item) = 0;
virtual void get(Int index) = 0;
};
template<class Item>
class ListOne : public AbstractList {
public:
virtual Iterator* createIterator() const;
...
};
Iterator* ListOne::createIterator() {
return new IteratorOne<Item>(this);
}
template<class Item>
class Iterator {
public:
virtual void first() = 0;
virtual void next() = 0;
virtual bool isEnd() const = 0;
virtual Item current() const = 0;
proteced:
Iterator();
};
template<class Item>
class IteratorOne : public Iterator {
public:
IteratorOne(const ListOne<Item>* list);
virtual void first();
virtual void next();
virtual bool isEnd() const;
virtual Item current() const;
private:
ListOne<Item>* m_list;
int m_index;
};
template<class Item>
void IteratorOne::first() {
m_index = 0;
}
template<class Item>
void IteratorOne::next() {
++m_index;
}
template<class Item>
bool IteratorOne::isEnd() const {
return m_index == m_list->count();
}
tempalte<class Item>
Item IteratorOne::current() const {
if(isEnd())
throw IteratorOutOfBounds();
return m_list->get(m_index);
}
ListOne<Book*> books;
IteratorOne<Book*>* iter = books.createIterator();
for(iter->first(); !iter->isEnd(); iter->next()) {
std::cout << iter->current()->print();
}
delete iter;
template<class Item>
class IteratorPtr {
public:
IteratorPtr(Iterator<Item>* iter) : m_iter(iter) {}
~IteratorPtr() { delete m_iter; }
Iterator<Item>* operator->() { returm m_iter; }
Iterator<Item>* operator*() { return *m_iter; }
private:
Iterator<Item>* m_iter;
}
ListOne<Book*> books;
IteratorPtr<Book*> iter(books.createIterator());
for(iter->first(); !iter->isEnd(); iter->next()) {
std::cout << iter->current()->print();
}
template<class Item>
class ListTraverser {
public:
ListTravrerser(ListOne<Item>* list);
void traverse();
proteced:
virtual void processItem(const Item&) = 0;
private:
IteratorOne<Item> m_iter;
};
void ListTraverser::traverse() {
bool result = false;
for(m_iter.first(); !m_iter.isEnd(); m_iter.next()) {
processItem(m_item.current());
}
}
void BookTraverse::processItem(const Book* book) {
cout << book;
}
List<Book> books;
BookTraverse bt(books);
bt.traverse();
Iterator - 迭代器模式,布布扣,bubuko.com
标签:style blog http color strong os
原文地址:http://blog.csdn.net/harrising/article/details/37998065