-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathiterator_pattern.py
98 lines (76 loc) · 1.88 KB
/
iterator_pattern.py
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
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
大话设计模式
设计模式——迭代器模式
迭代器模式(Iterator Pattern):提供方法顺序访问一个聚合对象中各元素,而又不暴露该对象的内部表示.
"""
#迭代器抽象类
class Iterator(object):
def First(self):
pass
def Next(self):
pass
def Isdone(self):
pass
def CurrItem(self):
pass
#聚集抽象类
class Aggregate(object):
def CreateIterator(self):
pass
#具体迭代器类
class ConcreteIterator(Iterator):
def __init__(self, aggregate):
self.aggregate = aggregate
self.curr = 0
def First(self):
return self.aggregate[0]
def Next(self):
ret = None
self.curr += 1
if self.curr < len(self.aggregate):
ret = self.aggregate[self.curr]
return ret
def Isdone(self):
return True if self.curr+1 >= len(self.aggregate) else False
def CurrItem(self):
return self.aggregate[self.curr]
#具体聚集类
class ConcreteAggregate(Aggregate):
def __init__(self):
self.ilist = []
def CreateIterator(self):
return ConcreteIterator(self)
class ConcreteIteratorDesc(Iterator):
def __init__(self, aggregate):
self.aggregate = aggregate
self.curr = len(aggregate)-1
def First(self):
return self.aggregate[-1]
def Next(self):
ret = None
self.curr -= 1
if self.curr >= 0:
ret = self.aggregate[self.curr]
return ret
def Isdone(self):
return True if self.curr-1<0 else False
def CurrItem(self):
return self.aggregate[self.curr]
if __name__=="__main__":
ca = ConcreteAggregate()
ca.ilist.append("大鸟")
ca.ilist.append("小菜")
ca.ilist.append("老外")
ca.ilist.append("小偷")
itor = ConcreteIterator(ca.ilist)
print itor.First()
while not itor.Isdone():
print itor.Next()
print "————倒序————"
itordesc = ConcreteIteratorDesc(ca.ilist)
print itordesc.First()
while not itordesc.Isdone():
print itordesc.Next()