在 面向對象程式設計裏,迭代器模式是一種設計模式,是一種最簡單也最多見的設計模式。它可讓使用者透過特定的接口巡訪容器中的每個元素而不用瞭解底層的實做。設計模式
定義:提供一種方法訪問一個容器對象中各個元素,而又不暴露該對象的內部細節。this
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Aggregate ag = new ConcreteAggregate(); ag.add("張三"); ag.add("李四"); ag.add("王五"); Iterator it = ag.iterator(); while(it.hasNext()){ String str = (String)it.next(); Console.WriteLine(str); } Console.Read(); } } public interface Iterator { Object next(); bool hasNext(); } public class ConcreteIterator : Iterator{ private ArrayList list = new ArrayList(); private int cursor =0; public ConcreteIterator(ArrayList list){ this.list = list; } public bool hasNext() { if(cursor==list.Count){ return false; } return true; } public Object next() { Object obj = null; if(this.hasNext()){ obj = this.list[cursor++]; } return obj; } } public interface Aggregate { void add(Object obj); void remove(Object obj); Iterator iterator(); } public class ConcreteAggregate : Aggregate { private ArrayList list = new ArrayList(); public void add(Object obj) { list.Add(obj); } public Iterator iterator() { return new ConcreteIterator(list); } public void remove(Object obj) { list.Remove(obj); } } }