今天我們一起看看行為模式中的迭代器模式,迭代是重復反饋過程的活動,其目的通常是為了接近并到達所需的目標或結果。在系統(tǒng)開發(fā)中簡單說可以理解成遍歷。這種模式用于順序訪問集合對象的元素,不需要知道集合對象的底層或者內部表示。
在系統(tǒng)開發(fā)中,集合對象內部表示各不相同。底層構造也盡不相同。對于這些對象,我們希望在不暴露其底層和內部表示的同時,可以使外部客戶訪問其中元素。迭代器模式就為這一需求提供了極其優(yōu)雅的實現(xiàn)。
提供一種方法順序訪問一個聚合對象中各個元素, 而又無須暴露該對象的內部表示。
我們從上面的案例圖可見,迭代器模式主要包含以下四個部分:
抽象迭代器:定義了訪問和遍歷元素的接口,然后在其子類中實現(xiàn)這些方法。
具體迭代器:實現(xiàn)抽象迭代器接口,完成對集合對象的遍歷。同時對遍歷時的位置進行跟蹤。
抽象聚合類:主要用于儲存對象,創(chuàng)建相應的迭代器對象的接口。帶有一個createIterator()方法用于創(chuàng)建迭代器對象。
具體聚合類:實現(xiàn)創(chuàng)建相應的迭代器對象的接口,實現(xiàn)createIterator()方法,并且返回與該具體聚合相對應的具體迭代器ConcreteIterator實例。
介紹完迭代器模式之后,接下來我們具體來看看迭代器模式的具體實現(xiàn)吧。具體如下:
namespace Iterator_Pattern{class IteratorPattern { }/// <summary>/// 抽象聚合類、包含一個創(chuàng)建迭代器對象的方法/// </summary>public interface IListAggregate { Iterator GetIterator(); }/// <summary>/// 抽象迭代器、包含訪問和遍歷元素的方法/// </summary>public interface Iterator {/// <summary>/// 是否有下一個元素/// </summary>/// <returns></returns>bool IsNext();/// <summary>/// 獲取當前元素位置/// </summary>/// <returns></returns>object GetCurrentIndex();/// <summary>/// 獲取下一個元素/// </summary>void Next();/// <summary>/// 獲取第一個元素、相當于重置/// </summary>void Start(); }/// <summary>/// 具體聚合類/// </summary>public class ConcreteListAggregate : IListAggregate { string[] list;public ConcreteListAggregate() { list = new string[] { "張三", "李四", "王五", "趙六" }; }/// <summary>/// 創(chuàng)建迭代器對象/// </summary>/// <returns></returns>public Iterator GetIterator() {return new ConcreteIterator(this); }/// <summary>/// 獲取對象長度/// </summary>public int Length {get { return list.Length; } }/// <summary>/// 獲取指定位置元素/// </summary>/// <param name="index"></param>/// <returns></returns>public object GetItem(int index) {return list[index]; } }public class ConcreteIterator : Iterator {private ConcreteListAggregate _list;private int _index;public ConcreteIterator(ConcreteListAggregate list) { _list = list; _index = 0; }public object GetCurrentIndex() {return _list.GetItem(_index); }public bool IsNext() {if (_index<_list.Length) {return true; }return false; }public void Next() {if (_index<_list.Length) { _index++; } }public void Start() { _index = 0; } }}
namespace Iterator_Pattern{class Program {static void Main(string[] args) {//獲取迭代器對象IListAggregate listAggregate = new ConcreteListAggregate(); Iterator iterator = listAggregate.GetIterator(); while (iterator.IsNext()) {var result = iterator.GetCurrentIndex(); Console.WriteLine(result); iterator.Next(); } } }}
1、訪問聚合對象的內容不需要暴露其內部表示。
2、需要為聚合對象提供多種遍歷方式。
3、為了遍歷不同的聚合結構對象提供統(tǒng)一的接口
1、訪問聚合對象內容時無需暴露其內部表示。
2、迭代器模式為不同的聚合結構對象提供了統(tǒng)一的接口。
3、在同一個聚合對象上可以實現(xiàn)多種遍歷。
4、增加新的聚合類和迭代類較為方便,無需修改之前的代碼
1、迭代器模式將存儲數(shù)據(jù)和遍歷數(shù)據(jù)的責任進行了分離。增加新的聚合類型的時候需要增加新的迭代器類。存在成對增加的。增加了系統(tǒng)的復雜性。
迭代器模式到這里就介紹完了。迭代器模式就是通過迭代器類將集合對象的遍歷行為進行區(qū)分開來。這樣一來就可以不暴露集合對象的內部表示了。又可以使外部能正常的使用訪問其元素。這個模式并不復雜。把握好其中每個角色的職責,進行連貫就好了。在.Net中我們也可以發(fā)現(xiàn)一個現(xiàn)成的迭代器模式。這也是最好的教程案例。IEnumerable作為了一個抽象聚合類、IEnumerator作為一個抽象迭代器。在System.Collections命名空間之下。有興趣深究的可以去研究下。