含义:提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示。
优点:1.它支持以不同的方式遍历一个聚合对象。
2.迭代器简化了聚合类。
3.在同一个聚合上可以有多个遍历。
4.在迭代器模式中,增加新的聚合类和迭代器类都很方便,无须修改原有代 码。
缺点:由于迭代器模式将存储数据和遍历数据的职责分离,增加新的聚合类需要对 应增加新的迭代器类,类的个数成对增加,这在一定程度上增加了系统的复杂性。
使用场景:1.访问一个聚合对象的内容而无须暴露它的内部表示。
2.需要为聚合对象提供多种遍历方式。
3.为遍历不同的聚合结构提供一个统一的接口。
C#示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IteratorPattern
{
/// <summary>
/// 顺序遍历接口
/// </summary>
public interface Iterator
{
bool hasNext();
Object next();
}
/// <summary>
/// 返回迭代器的接口
/// </summary>
public interface Container
{
Iterator getIterator();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IteratorPattern
{
public class NameRepository : Container
{
public static String[] names = { "Robert", "John", "Julie", "Lora" };
public Iterator getIterator()
{
return new NameIterator();
}
private class NameIterator : Iterator
{
int index;
public bool hasNext()
{
if (index < names.Length)
{
return true;
}
return false;
}
public Object next()
{
if (this.hasNext())
{
return names[index++];
}
return null;
}
}
}
}
执行部分:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace IteratorPattern
{
public partial class Form1 : Form
{
NameRepository namesRepository;
public Form1()
{
InitializeComponent();
namesRepository = new NameRepository();
}
private void button1_Click(object sender, EventArgs e)
{
for (Iterator iter = namesRepository.getIterator(); iter.hasNext(); )
{
String name = (String)iter.next();
listBox1.Items.Add("Name : " + name);
}
}
}
}