迭代器模式(Iterator Pattern)

时间:2022-05-22 08:30:28

标签:

原文:C#设计模式(16)——迭代器模式(Iterator Pattern)

一、引言

  在上篇博文中分享了我对命令模式的理解,命令模式主要是把行为进行抽象成命令,使得请求者的行为和接受者的行为形成低耦合。在一章中,将介绍一下迭代器模式。下面空话不久不多说了,直接进入本博文的主题。

二、迭代器模式的介绍

  迭代器是针对调集东西而生的,对付调集东西而言,一定涉及到调集元素的添加删除操纵,同时也必定撑持遍历调集元素的操纵,我们此时可以把遍历操纵也放在调集东西中,但这样的话,调集东西就承当太多的责任了,面向东西设计原则中有一条是单一职责原则,所以我们要尽可能地疏散这些职责,用差此外类去承当差此外职责。迭代器模式就是用迭代器类来承当遍历调集元素的职责。

2.1 迭代器模式的界说

  迭代器模式供给了一种要领挨次访谒一个聚合东西(理解为调集东西)中各个元素,而又无需袒露该东西的内部暗示,这样既可以做到不袒露调集的内部布局,又可让外部代码透明地访谒调集内部的数据。

2.2 迭代器模式的布局

  既然,迭代器模式承当了遍历调集东西的职责,,则该模式自然存在2个类,一个是聚合类,一个是迭代器类。在面向东西涉及原则中还有一条是针对接口编程,所以,在迭代器模式中,抽象了2个接口,一个是聚合接口,另一个是迭代器接口,这样迭代器模式中就四个角色了,具体的类图如下所示:

迭代器模式(Iterator Pattern)

  从上图可以看出,迭代器模式由以下角色构成:

迭代器角色(Iterator):迭代器角色卖力界说访谒和遍历元素的接口

具体迭代器角色(Concrete Iteraror):具体迭代器角色实现了迭代器接口,并需要记录遍历中确当前位置。

聚合角色(Aggregate):聚合角色卖力界说获得迭代器角色的接口

具体聚合角色(Concrete Aggregate):具体聚合角色实现聚合角色接口。

2.3 迭代器模式的实现

  介绍完迭代器模式之后,下面就具体看看迭代器模式的实现,具体实现代码如下:

1 // 抽象聚合类 2 public interface IListCollection 3 { 4 Iterator GetIterator(); 5 } 6 7 // 迭代器抽象类 8 public interface Iterator 9 { 10 bool MoveNext(); 11 Object GetCurrent(); 12 void Next(); 13 void Reset(); 14 } 15 16 // 具体聚合类 17 public class ConcreteList : IListCollection 18 { 19 int[] collection; 20 public ConcreteList() 21 { 22 collection = new int[] { 2, 4, 6, 8 }; 23 } 24 25 public Iterator GetIterator() 26 { 27 return new ConcreteIterator(this); 28 } 29 30 public int Length 31 { 32 get { return collection.Length; } 33 } 34 35 public int GetElement(int index) 36 { 37 return collection[index]; 38 } 39 } 40 41 // 具体迭代器类 42 public class ConcreteIterator : Iterator 43 { 44 // 迭代器要调集东西进行遍历操纵,自然就需要引用调集东西 45 private ConcreteList _list; 46 private int _index; 47 48 public ConcreteIterator(ConcreteList list) 49 { 50 _list = list; 51 _index = 0; 52 } 53 54 55 public bool MoveNext() 56 { 57 if (_index < _list.Length) 58 { 59 return true; 60 } 61 return false; 62 } 63 64 public Object GetCurrent() 65 { 66 return _list.GetElement(_index); 67 } 68 69 public void Reset() 70 { 71 _index = 0; 72 } 73 74 public void Next() 75 { 76 if (_index < _list.Length) 77 { 78 _index++; 79 } 80 81 } 82 } 83 84 // 客户端 85 class Program 86 { 87 static void Main(string[] args) 88 { 89 Iterator iterator; 90 IListCollection list = new ConcreteList(); 91 iterator = list.GetIterator(); 92 93 while (iterator.MoveNext()) 94 { 95 int i = (int)iterator.GetCurrent(); 96 Console.WriteLine(i.ToString()); 97 iterator.Next(); 98 } 99 100 Console.Read(); 101 } 102 }

自然,上面代码的运行功效也是对调集每个元素的输出,具体运行功效如下图所示:

迭代器模式(Iterator Pattern)

三、.NET中迭代器模式的应用