本文實例講述了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