23种设计模式(C++)之 迭代器(Iterator)模式
意图
提供一种方法顺序访问一个聚合对象中各个元素,而又不需暴露该对象的内部表示。
适用性
- 访问一个聚合对象的内容而无需暴露它的内部表示
- 支持对聚合对象的多种遍历
- 为遍历不同的聚合结构提供一个统一的接口。
场景
比如载有乘客的巴士,你可以顺序访问巴士中每一位乘客,但又无需知道巴士结构组成。乘客下车或上车,也不会影响你遍历巴士乘客的方式。
角色
- Iterator
- 迭代器定义访问和遍历元素的接口
- ConcreteIterator
- 具体迭代器实现迭代器接口
- 对该聚合遍历时跟踪当前的位置
- Aggregate
- 聚合定义,创建相应的迭代器对象的接口。
- ConcreteAggregate
- 具体聚合实现创建相应迭代器的接口,该操作返回ConcreteIterator的一个适当的实例。
实例
以遍历Bus上的Person为例:
- 创建Person类
class Person
{
private:
string name;
public:
Person(string name)
{
this->name = name;
}
string getName()
{
return this->name;
}
};
- 创建迭代器接口
class Iterator
{
protected:
Iterator() {}
public:
virtual ~Iterator() {};
virtual bool hasNext() = 0;
virtual Person* next() = 0;
};
- 创建聚合体接口
class Aggregate
{
public:
virtual Iterator* iterator() = 0;
};
- 创建Bus类
class Bus : public Aggregate
{
private:
vector<Person* > person_vec;
public:
void appendPerson(Person* person)
{
this->person_vec.push_back(person);
}
void removePerson(Person* person)
{
vector<Person* >::iterator it;
for (it = this->person_vec.begin(); it!=this->person_vec.end();)
{
if (*it == person)
{
it = this->person_vec.erase(it);
}
else
{
it++;
}
}
}
Person* getPersonByIndex(int index)
{
return this->person_vec.at(index);
}
int getPersonNum()
{
return this->person_vec.size();
}
Iterator* iterator();
};
- 创建Bus迭代器类
class BusIterator : public Iterator
{
private:
Bus* bus;
int index;
public:
BusIterator(Bus* bus)
{
this->bus = bus;
this->index = 0;
}
bool hasNext()
{
if (this->index < this->bus->getPersonNum())
{
return true;
}
return false;
}
Person* next()
{
Person* person = this->bus->getPersonByIndex(this->index);
this->index++;
return person;
}
};
Iterator* Bus::iterator()
{
return new BusIterator(this);
}
- 创建Client
int main()
{
Bus* bus = new Bus();
Person* hong = new Person("xiao hong");
bus->appendPerson(new Person("xiao ming"));
bus->appendPerson(hong);
bus->appendPerson(new Person("xiao hua"));
Iterator* it = bus->iterator();
cout << "*********************************************" << endl;
while (it->hasNext())
{
Person* person = it->next();
cout << person->getName() << endl;
}
cout << "*********************************************" << endl;
cout << "Remove a person" << endl;
bus->removePerson(hong);
it = bus->iterator();
while (it->hasNext())
{
Person* person = it->next();
cout << person->getName() << endl;
}
}
- 结果
*********************************************
xiao ming
xiao hong
xiao hua
*********************************************
Remove a person
xiao ming
xiao hua