迭代器模式(python)

來源:互聯網
上載者:User

迭代器模式:提供一種方法順序訪問一個彙總對象中的各個元素,而又不暴露該對象的內部表示。

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();

類圖

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.