迭代器是一种行为设计模式,让你能在不暴露集合底层表现形式(列表、栈和树等)的情况下遍历集合中所有的元素。
实例
Iterator.h
#ifndef ITERATOR_H_
#define ITERATOR_H_
#include <string>
// 抽象迭代器
class TVIterator{
public:
virtual void setChannel(int i) = 0;
virtual void next() = 0;
virtual void previous() = 0;
virtual bool isLast() = 0;
virtual std::string currentChannel() = 0;
virtual bool isFirst() = 0;
};
#endif // ITERATOR_H_
ConcreteIterator.h
#ifndef CONCRETE_ITERATOR_H_
#define CONCRETE_ITERATOR_H_
#include <string>
#include <vector>
#include "Iterator.h"
// 具体迭代器
class SkyworthIterator : public TVIterator{
public:
explicit SkyworthIterator(std::vector<std::string> &tvs) : tvs_(tvs) {}
void next() override {
if (current_index_ < tvs_.size()) {
current_index_++;
}
}
void previous() override {
if (current_index_ > 0) {
current_index_--;
}
}
void setChannel(int i) override {
current_index_ = i;
}
std::string currentChannel() override {
return tvs_[current_index_];
}
bool isLast() override {
return current_index_ == tvs_.size();
}
bool isFirst() override {
return current_index_ == 0;
}
private:
std::vector<std::string> &tvs_;
int current_index_ = 0;
};
#endif // CONCRETE_ITERATOR_H_
Collection.h
#ifndef COLLECTION_H_
#define COLLECTION_H_
#include <memory>
#include "Iterator.h"
// 抽象集合
class Television {
public:
virtual std::shared_ptr<TVIterator> createIterator() = 0;
};
#endif // COLLECTION_H_
ConcreteCollection.h
#ifndef CONCRETE_COLLECTION_H_
#define CONCRETE_COLLECTION_H_
#include <vector>
#include <string>
#include <memory>
#include "Collection.h"
#include "ConcreteIterator.h"
class SkyworthTelevision : public Television {
public:
std::shared_ptr<TVIterator> createIterator() {
return std::make_shared<SkyworthIterator>(tvs_);
}
void addItem(std::string item) {
tvs_.push_back(item);
}
private:
std::vector<std::string> tvs_;
};
#endif // CONCRETE_COLLECTION_H_
main.cpp
#include <iostream>
#include "ConcreteCollection.h"
int main() {
SkyworthTelevision stv;
stv.addItem("CCTV-1");
stv.addItem("CCTV-2");
stv.addItem("CCTV-3");
stv.addItem("CCTV-4");
stv.addItem("CCTV-5");
auto iter = stv.createIterator();
while (!iter->isLast()) {
std::cout << iter->currentChannel() << std::endl;
iter->next();
}
return 0;
}
编译运行:
$g++ main.cpp -std=c++11 -o iterator
$./iterator
CCTV-1
CCTV-2
CCTV-3
CCTV-4
CCTV-5