设计模式学习笔记——迭代器模式(Iterator)
1.特点:将对集合的访问与遍历从集合对象中分离出来到迭代器中。
2.概念:迭代器模式(Iterator)就是分离了聚合对象的遍历行为,抽象出一个迭代器来负责这样既可以做到不暴露集合的内部结构,又可让外部代码透明的访问集合内部数据。
3.类图:
4.程序实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | // 抽象聚合类 public interface IListCollection { Iterator GetIterator(); } // 迭代器抽象类 public interface Iterator { bool MoveNext(); Object GetCurrent(); void Next(); void Reset(); } // 具体聚合类 public class ConcreteList : IListCollection { int [] collection; public ConcreteList() { collection = new int [] { 2, 4, 6, 8 }; } public Iterator GetIterator() { return new ConcreteIterator( this ); } public int Length { get { return collection.Length; } } public int GetElement( int index) { return collection[index]; } } // 具体迭代器类 public class ConcreteIterator : Iterator { // 迭代器要集合对象进行遍历操作,自然就需要引用集合对象 private ConcreteList _list; private int _index; public ConcreteIterator(ConcreteList list) { _list = list; _index = 0; } public bool MoveNext() { if (_index < _list.Length) { return true ; } return false ; } public Object GetCurrent() { return _list.GetElement(_index); } public void Reset() { _index = 0; } public void Next() { if (_index < _list.Length) { _index++; } } } // 客户端 class Program { static void Main( string [] args) { Iterator iterator; IListCollection list = new ConcreteList(); iterator = list.GetIterator(); while (iterator.MoveNext()) { int i = ( int )iterator.GetCurrent(); Console.WriteLine(i.ToString()); iterator.Next(); } Console.Read(); } } |
分类:
设计模式
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构