Skip to content

Commit 6ace437

Browse files
committed
迭代器模式
1 parent 1fffa58 commit 6ace437

2 files changed

Lines changed: 102 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace IteratorPattern
8+
{
9+
/// <summary>
10+
/// 聚集的抽象
11+
/// </summary>
12+
abstract class Aggregate
13+
{
14+
public abstract Iterator CreateIterator();
15+
}
16+
17+
class ConcreteAggregate : Aggregate
18+
{
19+
private List<Object> items = new List<object>();
20+
21+
public override Iterator CreateIterator()
22+
{
23+
24+
}
25+
26+
public int Size()
27+
{
28+
return items.Count;
29+
}
30+
31+
public Object GetItem(int i)
32+
{
33+
return items[i];
34+
}
35+
36+
public void SetItems(int i,Object obj)
37+
{
38+
items[i] = obj;
39+
}
40+
}
41+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace IteratorPattern
8+
{
9+
/// <summary>
10+
/// 抽象的迭代器
11+
/// </summary>
12+
abstract class Iterator
13+
{
14+
public abstract Object First();
15+
public abstract Object Next();
16+
public abstract bool IsDone();
17+
public abstract Object CurrentItem();
18+
}
19+
20+
class ConcreteIterator : Iterator
21+
{
22+
private ConcreteAggregate aggregate;
23+
private int index = 0;
24+
public ConcreteIterator(ConcreteAggregate aggregate)
25+
{
26+
this.aggregate = aggregate;
27+
}
28+
public override object First()
29+
{
30+
return this.aggregate.GetItem(0);
31+
}
32+
33+
public override object Next()
34+
{
35+
Object obj = null;
36+
index++;
37+
if (index < this.aggregate.Size())
38+
{
39+
obj = this.aggregate.GetItem(index);
40+
}
41+
return obj;
42+
}
43+
44+
public override bool IsDone()
45+
{
46+
if (index >= this.aggregate.Size())
47+
{
48+
return true;
49+
}
50+
else
51+
{
52+
return false;
53+
}
54+
}
55+
56+
public override object CurrentItem()
57+
{
58+
return this.aggregate.GetItem(index);
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)