设计模式学习笔记--迭代器模式
Posted bzyzhang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式学习笔记--迭代器模式相关的知识,希望对你有一定的参考价值。
1 using System; 2 3 namespace Iterator 4 { 5 /// <summary> 6 /// 作者:bzyzhang 7 /// 时间:2016/5/30 20:01:24 8 /// 博客地址:http://www.cnblogs.com/bzyzhang/ 9 /// Iterator说明:迭代器抽象类 10 /// </summary> 11 public abstract class Iterator 12 { 13 public abstract object First(); 14 public abstract object Next(); 15 public abstract bool IsDone(); 16 public abstract object CurrentItem(); 17 } 18 }
1 using System; 2 3 namespace Iterator 4 { 5 /// <summary> 6 /// 作者:bzyzhang 7 /// 时间:2016/5/30 20:03:19 8 /// 博客地址:http://www.cnblogs.com/bzyzhang/ 9 /// Aggregate说明:聚集抽象类 10 /// </summary> 11 public abstract class Aggregate 12 { 13 public abstract Iterator CreateIterator(); 14 } 15 }
1 using System; 2 using System.Collections.Generic; 3 4 namespace Iterator 5 { 6 /// <summary> 7 /// 作者:bzyzhang 8 /// 时间:2016/5/30 20:06:13 9 /// 博客地址:http://www.cnblogs.com/bzyzhang/ 10 /// ConcreteAggregate说明:具体聚集类,继承Aggregate 11 /// </summary> 12 public class ConcreteAggregate:Aggregate 13 { 14 private List<object> items = new List<object>(); 15 16 public override Iterator CreateIterator() 17 { 18 return new ConcreteIterator(this); 19 } 20 21 public int Count 22 { 23 get 24 { 25 return items.Count; 26 } 27 } 28 29 public object this[int index] 30 { 31 get 32 { 33 return items[index]; 34 } 35 set 36 { 37 items.Insert(index,value); 38 } 39 } 40 } 41 }
1 using System; 2 3 namespace Iterator 4 { 5 /// <summary> 6 /// 作者:bzyzhang 7 /// 时间:2016/5/30 20:04:19 8 /// 博客地址:http://www.cnblogs.com/bzyzhang/ 9 /// ConcreteIterator说明:具体迭代器类,继承Iterator 10 /// </summary> 11 public class ConcreteIterator:Iterator 12 { 13 private ConcreteAggregate aggregate; 14 private int current = 0; 15 16 public ConcreteIterator(ConcreteAggregate aggregate) 17 { 18 this.aggregate = aggregate; 19 } 20 21 public override object First() 22 { 23 return aggregate[0]; 24 } 25 26 public override object Next() 27 { 28 object ret = null; 29 ++current; 30 if(current <aggregate.Count) 31 ret = aggregate[current]; 32 return ret; 33 } 34 35 public override bool IsDone() 36 { 37 return current >= aggregate.Count ? true : false; 38 } 39 40 public override object CurrentItem() 41 { 42 return aggregate[current]; 43 } 44 } 45 }
1 using System; 2 3 namespace Iterator 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 ConcreteAggregate a = new ConcreteAggregate(); 10 11 a[0] = "大鸟"; 12 a[1] = "小菜"; 13 a[2] = "行李"; 14 a[3] = "老外"; 15 a[4] = "公交内部员工"; 16 a[5] = "小偷"; 17 18 Iterator iterator = new ConcreteIterator(a); 19 20 object item = iterator.First(); 21 22 while (!iterator.IsDone()) 23 { 24 Console.WriteLine("{0}请买车票!",iterator.CurrentItem()); 25 iterator.Next(); 26 } 27 } 28 } 29 }
以上是关于设计模式学习笔记--迭代器模式的主要内容,如果未能解决你的问题,请参考以下文章