head first 设计模式学习随笔(9)---迭代器模式

所谓迭代器模式,就是实现一个迭代器接口,从而实现对通用对象组的遍历,而又不暴露内部结构

以下以鸭子和虫子为例说明:

 

Code
/// <summary>
/// 迭代器模式接口
/// </summary>
public interface Iterator
{
bool HasNext();
object Next();
}

/// <summary>
/// 一种带数组成员类
/// </summary>
public class Worms : Iterator
{
string[] worms;
int nums = -1;

public Worms(string[] worms)
{
this.worms = worms;
}

#region Iterator Members

public bool HasNext()
{
if (worms.Length > nums + 1)
{
nums
+= 1;
return true;
}
else
return false;
}

public object Next()
{
return worms[nums];
}

#endregion
}


/// <summary>
/// 一种带泛型成员类
/// </summary>
public class Duck : Iterator
{
List
<string> ducks;
int nums = -1;

public Duck(List<string> ducks)
{
this.ducks = ducks;
}
#region Iterator Members

public bool HasNext()
{
if (ducks.Count > nums+1)
{
nums
+= 1;
return true;
}
else
return false;
}

public object Next()
{
return ducks[nums];
}

#endregion
}


public class Info
{
Worms worms;
Duck ducks;

public Info(Worms worms,Duck ducks)
{
this.worms = worms;
this.ducks = ducks;
}

public void ReadIterator(string type)
{
if (type == "ducks")
Read(ducks);
if (type == "worms")
Read(worms);
}

//统一遍历接口
private void Read(Iterator i)
{
while(i.HasNext())
Console.WriteLine(i.Next().ToString());
}
}


class Program
{
static void Main(string[] args)
{
Worms worms
= new Worms(new string[] { "毛毛虫", "鼻涕虫", "蚂蚁", "苍蝇", "蚊子", "瓢虫", "蟋蟀", "蜈蚣" });
Duck ducks
= new Duck(new List<string> { "鸳鸯", "", "黄头鸭", "北京填鸭", "绿头鸭", "白头鸭", "黑鸭鸭", "白鸭鸭", "长嘴鸭", "无毛鸭" });

Info info
= new Info(worms, ducks);

info.ReadIterator(
"ducks");
Console.WriteLine(
"-------------华丽的分割线----------------");
info.ReadIterator(
"worms");

Console.Read();
}
}

 

 head first 设计模式学习随笔(9)---迭代器模式

你可能感兴趣的:(迭代器模式)