设计模式-迭代器模式
迭代器模式(Iterator Pattern),提供一种方法顺序访问一个聚合对象中元素,而不暴露该集合对象的内部表示。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PatternProject
{
public class People
{
public string name
{ get; set; }
public string sex
{ get; set; }
public int age
{ get; set; }
public DateTime JoinDateTime
{ get; set; }
public People(string name, string sex, int age)
{
this.name = name;
this.sex = sex;
this.age = age;
this.JoinDateTime = DateTime.Now;
}
}
public interface ISearcher
{
bool Next(); //在迭代时,判断是否能获取下一个,外部遍历必需实现该方法
}
public interface IProvince
{
ISearcher GetSearcher(); //获取迭代器对象
}
public class Province : IProvince
{
List<People> peopleList = new List<People>();
public string name
{ get; set; }
public Province(string name)
{
this.name = name;
}
public ISearcher GetSearcher()
{
return new Searcher(this, "黄某", "男", 45);
}
public People this[int index]
{
get { return peopleList[index]; }
//set { peopleList.Add(value); }
}
public void Join(People people)
{
peopleList.Add(people);
}
public int GetPeopleCount()
{
return peopleList.Count;
}
}
public class Searcher : People, ISearcher
{
Province _province;
int _currentIndex;
public Searcher(Province province, string name, string sex, int age)
: base(name, sex, age)
{
_province = province;
_currentIndex = -1;
}
public People Current
{
get { return _province[_currentIndex]; }
}
public bool Next()
{
_currentIndex++;
return _province.GetPeopleCount() > _currentIndex;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PatternProject
{
class Program
{
static void Main(string[] args)
{
Province SZProvince = new Province("深圳市");
SZProvince.Join(new People("张三", "男", 25));
SZProvince.Join( new People("李四", "男", 35));
SZProvince.Join(new People("王五", "男", 30));
SZProvince.Join(new People("赵六", "男", 28));
SZProvince.Join(new People("谢七", "女", 20));
Console.WriteLine("{0}共计人口:{1}人", SZProvince.name, SZProvince.GetPeopleCount());
Searcher srh= (Searcher)SZProvince.GetSearcher();
Console.WriteLine("人口检查官:{0}人口普查结果如下:", srh.name);
while (srh.Next())
{
People p=srh.Current;
Console.WriteLine("{0},{1},{2}岁于{3}入住;", p.name, p.sex, p.age, p.JoinDateTime);
}
Console.ReadKey();
}
}
}
浙公网安备 33010602011771号