1. 迭代器模式(Iterator)介紹
UML類圖
角色介紹
- 抽象容器:一般是一個接口,提供一個iterator()方法。
- 具體容器:就是抽象容器的具體實現類,比如List接口的有序列表實現ArrayList,List接口的鏈表實現LinkList,Set接口的哈希列表的實現HashSet等。
- 抽象迭代器:定義遍歷元素所需要的方法,一般來說會有這麼三個方法:取得第一個元素的方法first(),取得下一個元素的方法next(),判斷是否遍歷結束的方法isDone()(或者叫hasNext()),移出當前對象的方法remove(),
- 迭代器實現:實現迭代器接口中定義的方法,完成集合的迭代。
用途
提供方法順序訪問一個聚合對象中各元素,而又不暴露該對象的內部表示。
2. 示例
"""Iterator Pattern with Python Code
"""
from abc import abstractmethod, ABCMeta
# 迭代器抽象類
class Iterator(metaclass=ABCMeta):
@abstractmethod
def First(self):
pass
@abstractmethod
def Next(self):
pass
@abstractmethod
def Isdone(self):
pass
@abstractmethod
def CurrItem(self):
pass
# 聚集抽象類
class Aggregate(metaclass=ABCMeta):
@abstractmethod
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]
class Client(object):
def main(self):
ca = ConcreteAggregate()
ca.ilist.append("1")
ca.ilist.append("2")
ca.ilist.append("3")
ca.ilist.append("4")
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())
if __name__=="__main__":
Client().main()
輸出
# ./Iterator.py
1
2
3
4
倒序:
4
3
2
1
參考:
https://wiki.jikexueyuan.com/project/java-design-pattern/iterator-pattern.html
https://www.cnblogs.com/onepiece-andy/p/python-iterator-pattern.html