C#迭代器模式分析
C#迭代器有很多值得學(xué)習(xí)的地方,這里我們主要介紹C#迭代器模式,包括介紹ICollection負(fù)責(zé)數(shù)據(jù)存儲(chǔ)等方面。
提到C#迭代器我們不能不想到C#迭代器模式,那我就以C#迭代器模式作為開場白。
在我們的應(yīng)用程序中常常有這樣一些數(shù)據(jù)結(jié)構(gòu):
它們是一個(gè)數(shù)據(jù)的集合,如果你知道它們內(nèi)部的實(shí)現(xiàn)結(jié)構(gòu)就可以去訪問它們,它們各自的內(nèi)部存儲(chǔ)結(jié)構(gòu)互不相同,各種集合有各自的應(yīng)用場合.說到這里大家可能想出一大堆這樣的集合了:List,Hashtable,ArrayList等等。這些集合各自都有各自的個(gè)性,這就是它們存在的理由。但如果你想遍歷它你必須知道它內(nèi)部的存儲(chǔ)細(xì)節(jié),作為一個(gè)集合元素,把內(nèi)部細(xì)節(jié)暴露出來肯定就不好了,這樣客戶程序就不夠穩(wěn)定了,在你更換集合對(duì)象的時(shí)候,比如List 不能滿足需求的時(shí)候,你換成Hashtable,因?yàn)橐郧暗目蛻舫绦蜻^多的關(guān)注了List內(nèi)部實(shí)現(xiàn)的細(xì)節(jié),所以不能很好的移植。而C#迭代器模式就是為解決這個(gè)問題而生的:
提供一種一致的方式訪問集合對(duì)象中的元素,而無需暴露集合對(duì)象的內(nèi)部表示。
比如現(xiàn)在有這樣一個(gè)需求,遍歷集合內(nèi)的元素,然后輸出,但是并不限定集合是什么類型的集合,也就是未來集合可能發(fā)生改變。
思考:
集合會(huì)發(fā)生改變,這是變化點(diǎn),集合改變了,遍歷方法也改變,我們要保證遍歷的方法穩(wěn)定,那么就要屏蔽掉細(xì)節(jié)。找到了變化點(diǎn)那我們就將其隔離起來(一般使用interface作為隔離手段):假設(shè)所有的集合都繼承自ICollection接口,這個(gè)接口用來隔離具體集合的,將集合屏蔽在接口后面,作為遍歷我們肯定需要這樣一些方法:MoveNext,Current,既然ICollection負(fù)責(zé)數(shù)據(jù)存儲(chǔ),職責(zé)又要單一,那么就新建立一個(gè)接口叫做 Iterator吧,每種具體的集合都有自己相對(duì)應(yīng)的Iterator實(shí)現(xiàn):
- public interface ICollection
- {
- int Count { get; }
- ///
- /// 獲取迭代器
- ///
- /// 迭代器
- Iterator GetIterator();
- }
- ///
- /// 迭代器接口
- ///
- public interface Iterator
- {
- bool MoveNext();
- object Current { get; }
- }
- public class List : ICollection
- {
- private const int MAX = 10;
- private object[] items;
- public List()
- {
- items = new object[MAX];
- }
- public object this[int i]
- {
- get { return items[i]; }
- set { this.items[i] = value; }
- }
- #region ICollection Members
- public int Count
- {
- get { return items.Length; }
- }
- public Iterator GetIterator()
- {
- return new ListIterator(this);
- }
- #endregion
- }
- public class ListIterator : Iterator
- {
- private int index = 0;
- private ICollection list;
- public ListIterator(ICollection list)
- {
- this.list = list;
- index = 0;
- }
- #region Iterator Members
- public bool MoveNext()
- {
- if (index + 1 > list.Count)
- return false;
- else
- {
- index++;
- return true;
- }
- }
- public object Current
- {
- get { return list[index]; }
- }
- #endregion
- }
- ///
- /// 測試
- ///
- public class Program
- {
- static void Main()
- {
- ICollection list = new List();
- Iterator iterator = list.GetIterator();
- while (iterator.MoveNext())
- {
- object current = iterator.Current;
- }
- }
- }
【編輯推薦】