Iterator.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace IteratorPattern
  7. {
  8. // 抽象聚合类
  9. public interface IListCollection
  10. {
  11. Iterator GetIterator();
  12. }
  13. // 迭代器抽象类
  14. public interface Iterator
  15. {
  16. bool MoveNext();
  17. Object GetCurrent();
  18. void Next();
  19. void Reset();
  20. }
  21. // 具体聚合类
  22. public class ConcreteList : IListCollection
  23. {
  24. readonly string[] _collection;
  25. public ConcreteList()
  26. {
  27. _collection = new string[] { "A", "B", "C", "D" };
  28. }
  29. public Iterator GetIterator()
  30. {
  31. return new ConcreteIterator(this);
  32. }
  33. public int Length
  34. {
  35. get { return _collection.Length; }
  36. }
  37. public string GetElement(int index)
  38. {
  39. return _collection[index];
  40. }
  41. }
  42. // 具体迭代器类
  43. public class ConcreteIterator : Iterator
  44. {
  45. // 迭代器要集合对象进行遍历操作,自然就需要引用集合对象
  46. private ConcreteList _list;
  47. private int _index;
  48. public ConcreteIterator(ConcreteList list)
  49. {
  50. _list = list;
  51. _index = 0;
  52. }
  53. public bool MoveNext()
  54. {
  55. if (_index < _list.Length)
  56. {
  57. return true;
  58. }
  59. return false;
  60. }
  61. public Object GetCurrent()
  62. {
  63. return _list.GetElement(_index);
  64. }
  65. public void Reset()
  66. {
  67. _index = 0;
  68. }
  69. public void Next()
  70. {
  71. if (_index < _list.Length)
  72. {
  73. _index++;
  74. }
  75. }
  76. }
  77. }