设计模式(23)---迭代器模式
定义:
迭代器模式,提供了一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
因为迭代器模式的广泛运用,现在高级语言如c#,java等本身已经把这个模式封装在语言当中。例如:c#中的foreach in。
因此此处暂不对迭代器模式做详细的介绍,下面简单讲述在书中看到的一些基础知识:
IEumerator支持对非泛型集合的简单迭代接口。
public interface IEumerator { object Current { get; } bool MoveNext(); void Reset(); }
IEnumerable公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。
public interface IEnumerable { IEumerator GetEnumerator(); }
简单举例:
IList<string> strList = new List<string>(); strList.Add("a"); strList.Add("c"); strList .Add ("d"); foreach (string item in strList) { Console.WriteLine("{0}", item); }
基本实现:
abstract class Iterator { public abstract object First(); public abstract object Next(); public abstract object CurrentItem(); public abstract bool IsDone(); } class ConcreteIterator:Iterator { private ConcreteAggregate aggregate; private int current = 0; public ConcreteIterator(ConcreteAggregate aggregate) { this.aggregate = aggregate; } public override object First() { return aggregate[0]; } public override object Next() { object obj = null; current ++; if (current < aggregate.Count) obj = aggregate[current]; return obj; } public override object CurrentItem() { return aggregate[current]; } public override bool IsDone() { return current >= aggregate.Count ? true : false; } } abstract class Aggregate { public abstract Iterator CreateIterator(); } class ConcreteAggregate : Aggregate { private IList<object> items = new List<object>(); public int Count { get { return items.Count; } } public object this[int index] { get { return items[index]; } set { items.Insert(index, value); } } public override Iterator CreateIterator() { return new ConcreteIterator(this); } }
客户端调用:
ConcreteAggregate agg = new ConcreteAggregate(); agg[0] = "张三"; agg[1] = "李四"; agg[2] = "王五"; agg[3] = "麻子"; Iterator it = new ConcreteIterator(agg); object item = it.First(); while (!it.IsDone()) { Console.WriteLine("{0}点到名字了", it.CurrentItem()); it.Next(); }
项目中实现迭代器的实例:
public class StudentInfo { public int Id; public string Name; public StudentInfo(int id, string name) { this.Id = id; this.Name = name; } } public class SchoolInfo : IEnumerable { public StudentInfo[] stu = new StudentInfo[] { new StudentInfo(1, "tom"), new StudentInfo(2, "jack"), new StudentInfo(3, "john") }; public IEnumerator GetEnumerator() { return this.stu.GetEnumerator(); } }
客户端调用:
SchoolInfo info = new SchoolInfo(); foreach (StudentInfo item in info.stu) Console.WriteLine("Id is {0},Name is {1}", item.Id, item.Name);
结果显示如下:
此外还可以查看Foreach遍历
//
最新博客信息,请关注“小项目笔记”公众号;