迭代器模式:提供一種方法順序訪問一個彙總對象中的各個元素,而又不暴露該對象的內部表示。
python內建支援這種模式,所以一般來說,不用自己寫,
#encoding=utf-8##by panda#迭代器(Iterator)模式def printInfo(info): print unicode(info, 'utf-8').encode('gbk')#迭代器抽象類別class Iterator: def First(self): pass def Next(self): pass def IsDone(self): pass def CurrentItem(self): pass #集合抽象類別class Aggregate: def CreateIterator(self): pass #具體迭代器類:class ConcreteIterator(Iterator): aggregate = None current = 0 def __init__(self, aggregate): self.aggregate = aggregate self.current = 0 def First(self): return self.aggregate[0] def Next(self): ret = None self.current += 1 if(self.current < len(self.aggregate)): ret = self.aggregate[self.current] return ret def IsDone(self): if(self.current < len(self.aggregate)): return False else: return True def CurrentItem(self): ret = None if(self.current < len(self.aggregate)): ret = self.aggregate[self.current] return ret #具體集合類class ConcreteAggregate(Aggregate): items = None def __init__(self): self.items = [] def clientUI(): a = ConcreteAggregate() a.items.append('大鳥') a.items.append('小菜') a.items.append('行李') a.items.append('老外') a.items.append('公交內部員工') a.items.append('小偷') printInfo('---------迭代器模式-------------') i = ConcreteIterator(a.items) item = i.First() while(False == i.IsDone()): printInfo("%s 請買車票!" % i.CurrentItem()); i.Next() printInfo('\n---------python內部迭代-------------') for item in a.items: printInfo("%s 請買車票!" % item); returnif __name__ == '__main__': clientUI();
類圖: