歡迎您光臨本站 註冊首頁

迭代器模式(python)

←手機掃碼閱讀     火星人 @ 2014-03-12 , reply:0
  
  迭代器模式:提供一種方法順序訪問一個聚合對象中的各個元素,而又不暴露該對象的內部表示。

  python內置支持這種模式,所以一般來說,不用自己寫,

  view plain #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);return

  if __name__ == '__main__':clientUI();



[火星人 ] 迭代器模式(python)已經有419次圍觀

http://coctec.com/docs/program/show-post-71481.html