设计模式之迭代器模式
来源:互联网 发布:iconkit for mac 破解 编辑:程序博客网 时间:2024/05/21 15:41
说起迭代器,大家一定不陌生,经常使用的foreach in 这种循环就是,C#语言已经内置化了迭代器模式,主要是支持对非泛型集合的简单迭代接口IEumerator和公开枚举数IEnumerable。虽然内置了,但是这种模式也有我们学习的必要性。
代码如下
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 设计模式之迭代器模式{ public abstract class Iterator//抽象迭代器 { public abstract object First(); public abstract object Next(); public abstract object Current(); public abstract bool IsMax(); } public abstract class Aggregate//抽象被迭代的对象 { public abstract Iterator CreateIterator(); } public class AIterator : Iterator//具体的迭代器 { public AAggregate listA = new AAggregate();//存放被迭代的对象 private int current=0; public AIterator(AAggregate a)//初始化时绑定被迭代的对象 { listA = a; } public override object First()//获得第一个迭代的对象 { return listA[0]; } public override object Next()//获得当前对象的下一个对象 { current++; if (current < listA.Count()) { return listA[current]; } else { return null; } } public override object Current()//获得当前对象 { return listA[current]; } public override bool IsMax() { return current == listA.Count() ? true : false; } } public class AAggregate : Aggregate//具体的被迭代对象,迭代方向是正向。 { public IList<object> lists = new List<object>(); public override Iterator CreateIterator()//创被迭代对象的造迭代器 { return new AIterator(this); } public int Count()//获得被迭代对象的个数 { return lists.Count; } public object this[int index]//索引器 { get { return lists[index]; } set { lists.Insert(index, value); } } } public class BIterator : Iterator { public AAggregate blist = new AAggregate(); private int current=0; public BIterator(AAggregate a) { blist = a; current = a.Count() - 1; } public override object Current() { return blist[current]; } public override object First() { return blist[blist.Count()-1]; } public override bool IsMax() { return current<0? true : false; } public override object Next() { current--; if(current>=0) { return blist[current]; } return null; } } class Program { static void Main(string[] args) { AAggregate a = new AAggregate(); a[0] = "你好"; a[1] = "你真的好吗?"; a[2] = "你他妈有病啊!老子很好"; AIterator b = new AIterator(a); while(!b.IsMax()) { Console.WriteLine(b.Current()); b.Next(); } Console.WriteLine(); BIterator c = new BIterator(a); while(!c.IsMax()) { Console.WriteLine(c.Current()); c.Next(); } Console.Read(); } }}
运行结果:
0 0
- 设计模式之迭代器模式
- 设计模式之 迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之--迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之-迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- 设计模式 之 迭代器模式
- 设计模式 之 迭代器模式
- 设计模式之迭代器模式
- 设计模式之迭代器模式
- ASIHTTPRequest的使用——大文件断点续传
- 正则表达式—应用实例
- 传神联合(北京)信息技术有限公司
- trie
- 视频会议系统怎样用比较稳定
- 设计模式之迭代器模式
- Oracle之内存结构(SGA、PGA)
- Android:gravity 和 android:layout_gravity属性
- ASIHTTPRequest的使用——下载文件
- activity
- 博客第二天-java基础的学习收获
- 常用的日期格式
- swift 与JavaScript之间方法的相互调用及传值
- Oracle内存结构:SGA PGA UGA