迭代器模式(Iterator Pattern),提供一种方法顺序访问一个聚合对象中元素,而不暴露该集合对象的内部表示。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
|
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();
}
}
}
|
本文转自 梦在旅途 博客园博客,原文链接:http://www.cnblogs.com/zuowj/p/3504610.html ,如需转载请自行联系原作者