本文实例讲述了python设计模式之迭代器模式原理与用法。分享给大家供大家参考,具体如下:
迭代器模式(iterator pattern):提供方法顺序访问一个聚合对象中各元素,而又不暴露该对象的内部表示.
下面是一个迭代器模式的demo:
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
|
#!/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 () |
运行结果:
上面类的设计如下图:
当需要对聚集有多种方式遍历时,可以考虑使用迭代器模式
迭代器模式分离了集合的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合内部结构,又可以让外部代码透明的访问集合内部的数据
希望本文所述对大家python程序设计有所帮助。
原文链接:https://www.cnblogs.com/onepiece-andy/p/python-iterator-pattern.html