定义:提供一种方法顺序访问一个聚合对象中的所有元素而不暴露该对象的内部表示。
UML类图:
C++实现:
#include<iostream>
#include<string>
#include<mutex>
#include<stack>
#include<vector>
using namespace std;
class NameIterator;
class Iterator
{
public:
virtual bool hasNext() = 0;
virtual string next() = 0;
virtual ~Iterator() = default;
};
class Container
{
public:
virtual Iterator* getIterator() = 0;
virtual ~Container() = default;
};
class NameRepository;
class NameIterator;
class NameRepository :public Container
{
public:
vector<string> names = { "Robert", "John", "Julie", "Lora" };
Iterator* getIterator();
virtual ~NameRepository() {}
};
class NameIterator :public Iterator
{
int index = 0;
NameRepository* nameRepository;
public:
NameIterator(NameRepository* nameRepository);
bool hasNext();
string next();
virtual ~NameIterator() {}
};
Iterator* NameRepository::getIterator()
{
return new NameIterator(this);
}
NameIterator::NameIterator(NameRepository* nameRepository)
{
this->nameRepository = nameRepository;
}
bool NameIterator::hasNext()
{
if (index < nameRepository->names.size())
{
return true;
}
return false;
}
string NameIterator::next()
{
if (this->hasNext())
{
return nameRepository->names[index++];
}
return nullptr;
}
int main()
{
NameRepository* nameRepository = new NameRepository();
for (Iterator* iter = nameRepository->getIterator(); iter->hasNext();)
{
string name = iter->next();
cout << "Name: " << name << endl;
}
return 0;
}
C#实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using static System.Console;
namespace ConsoleApp1
{
public interface Iterator
{
bool hasNext();
object next();
}
public interface Container
{
Iterator getIterator();
}
public class NameRepository : Container
{
public String[] names = { "Robert", "John", "Julie", "Lora" };
public Iterator getIterator()
{
return new NameIterator(this);
}
}
public class NameIterator : Iterator
{
int index;
NameRepository nameRepository;
public NameIterator(NameRepository nameRepository)
{
this.nameRepository = nameRepository;
}
public bool hasNext()
{
if (index < nameRepository.names.Length)
{
return true;
}
return false;
}
public object next()
{
if(this.hasNext())
{
return nameRepository.names[index++];
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
NameRepository nameRepository = new NameRepository();
for(Iterator iter=nameRepository.getIterator();iter.hasNext();)
{
String name = (String)iter.next();
WriteLine("Name: " + name);
}
}
}
}