github地址:https://github.com/cheesezh/python_design_patterns

迭代器模式

迭代器模式,提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示[DP]。

当需要访问一个聚集对象,而且不管这些对象是什么都需要遍历的时候,就应该考虑使用迭代器模式。

当需要对聚集有多种方式遍历时,也可以考虑使用迭代器模式。

迭代器为遍历不同的聚集结构提供如开始,下一个,是否结束,当前哪一项等统一接口。

from abc import ABCMeta, abstractmethod

class Iterator():
"""
迭代器抽象类,定义得到开始对象,得到下一对象,判断是否结尾,得到当前对象等方法
"""
__metaclass__ = ABCMeta @abstractmethod
def first(self):
pass @abstractmethod
def next(self):
pass @abstractmethod
def is_done(self):
pass @abstractmethod
def current_item(self):
pass class Aggregate():
"""
聚集抽象类
"""
__metaclass__ = ABCMeta @abstractmethod
def create_iterator(self):
pass class ConcreteIterator(Iterator):
"""
具体迭代器类
"""
def __init__(self, aggregate):
# 定义一个具体的聚集对象,初始化时将具体的聚集对象传入
self.aggregate = aggregate
self.current = 0 def first(self):
# 得到聚集的第一个对象
return self.aggregate.get_value(0) def next(self):
# 得到聚集的下一个对象
ret = None
self.current += 1
if self.current < self.aggregate.length:
ret = self.aggregate.get_value(self.current)
return ret def is_done(self):
return True if self.current >= self.aggregate.length else False def current_item(self):
return self.aggregate.get_value(self.current) class ConcreteAggregate(Aggregate):
"""
具体聚集类
"""
def __init__(self):
self.list = []
self.length = 0 def create_iterator(self):
return ConcreteIterator(self) def create_iterator_desc(self):
return ConcreteIteratorDesc(self) def insert_value(self, value):
self.list.append(value)
self.length += 1 def get_value(self, index):
return self.list[index] def main():
agg = ConcreteAggregate()
agg.insert_value("aa")
agg.insert_value("bb")
agg.insert_value("cc")
agg.insert_value("dd")
agg.insert_value("ee") i = agg.create_iterator() item = i.first()
while i.is_done() == False:
print("{} 买车票".format(i.current_item()))
i.next() main()
aa 买车票
bb 买车票
cc 买车票
dd 买车票
ee 买车票

逆序遍历

class ConcreteIteratorDesc(Iterator):
"""
具体迭代器类,逆序遍历
"""
def __init__(self, aggregate):
# 定义一个具体的聚集对象,初始化时将具体的聚集对象传入
self.aggregate = aggregate
self.current = self.aggregate.length-1 def first(self):
# 得到聚集的第一个对象
return self.aggregate.get_value(self.aggregate.length-1) def next(self):
# 得到聚集的下一个对象
ret = None
self.current -= 1
if self.current >= 0:
ret = self.aggregate.get_value(self.current)
return ret def is_done(self):
return True if self.current < 0 else False def current_item(self):
return self.aggregate.get_value(self.current) def main():
agg = ConcreteAggregate()
agg.insert_value("aa")
agg.insert_value("bb")
agg.insert_value("cc")
agg.insert_value("dd")
agg.insert_value("ee") i = agg.create_iterator_desc() item = i.first()
while i.is_done() == False:
print("{} 买车票".format(i.current_item()))
i.next() main()
ee 买车票
dd 买车票
cc 买车票
bb 买车票
aa 买车票

点评

总的来说,迭代器模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可以让外部代码透明的访问集合内部的数据。

[Python设计模式] 第20章 挨个买票——迭代器模式的更多相关文章

  1. [Python设计模式] 第24章 加薪审批——职责链模式

    github地址:https://github.com/cheesezh/python_design_patterns 题目 用程序模拟以下情景 员工向经理发起加薪申请,经理无权决定,需要向总监汇报, ...

  2. [Python设计模式] 第8章 学习雷锋好榜样——工厂方法模式

    github地址:https://github.com/cheesezh/python_design_patterns 简单工厂模式 v.s. 工厂方法模式 以简单计算器为例,对比一下简单工厂模式和工 ...

  3. [Python设计模式] 第28章 男人和女人——访问者模式

    github地址:https://github.com/cheesezh/python_design_patterns 题目 用程序模拟以下不同情况: 男人成功时,背后多半有一个伟大的女人: 女人成功 ...

  4. [Python设计模式] 第18章 游戏角色备份——备忘录模式

    github地址:https://github.com/cheesezh/python_design_patterns 题目 用代码模拟以下场景,一个游戏角色有生命力,攻击力,防御力等数据,在打Bos ...

  5. 设计模式(十):从电影院中认识"迭代器模式"(Iterator Pattern)

    上篇博客我们从醋溜土豆丝与清炒苦瓜中认识了“模板方法模式”,那么在今天这篇博客中我们要从电影院中来认识"迭代器模式"(Iterator Pattern).“迭代器模式”顾名思义就是 ...

  6. 设计模式学习笔记(十六)迭代器模式及其在Java 容器中的应用

    迭代器(Iterator)模式,也叫做游标(Cursor)模式.我们知道,在Java 容器中,为了提高容器遍历的方便性,把遍历逻辑从不同类型的集合类中抽取出来,避免向外部暴露集合容器的内部结构. 一. ...

  7. [Python设计模式] 第21章 计划生育——单例模式

    github地址:https://github.com/cheesezh/python_design_patterns 单例模式 单例模式(Singleton Pattern)是一种常用的软件设计模式 ...

  8. [Python设计模式] 第1章 计算器——简单工厂模式

    github地址:https://github.com/cheesezh/python_design_patterns 写在前面的话 """ 读书的时候上过<设计模 ...

  9. [Python设计模式] 第26章 千人千面,内在共享——享元模式

    github地址:https://github.com/cheesezh/python_design_patterns 背景 有6个客户想做产品展示网站,其中3个想做成天猫商城那样的"电商风 ...

随机推荐

  1. BZOJ2527 [Poi2011]Meteors 整体二分 树状数组

    原文链接http://www.cnblogs.com/zhouzhendong/p/8686460.html 题目传送门 - BZOJ2527 题意 有$n$个国家. 太空里有$m$个太空站排成一个圆 ...

  2. 033 Url中特殊字符的处理

    在url跳转页面的时候,参数值中的#不见了,一直没有处理,今天有空看了一下,后来发现后台的过滤器之类的都没有处理,就比较奇怪了,原来是特殊字符的问题. 一:Url中的特殊字符 1.说明 这里还是需要做 ...

  3. 013 mysql中find_in_set()函数的使用

    在工作中遇见过,对于新知识,在这里写一写文档. 1.作用 举个例子,也许不理解,在看完后面的SQL示例,再来看就明白了: 有个文章表里面有个type字段,它存储的是文章类型,有 1头条.2推荐.3热点 ...

  4. SpringBoot统一错误处理

    1.处理错误请求页面 import org.springframework.stereotype.Controller; import org.springframework.web.bind.ann ...

  5. mybatis sql注入

    这是${}与#{}的区别,#{}采用了预编译,在SQL执行前,会先将上面的SQL发送给数据库进行编译:执行时,直接使用编译好的SQL,替换占位符“?”就可以了.因为SQL注入只能对编译过程起作用,所以 ...

  6. Petya and Array CodeForces - 1042D (树状数组)

    D. Petya and Array time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  7. P2661 信息传递

    P2661 信息传递dfs求最小环,要加时间戳,记录这个点是哪一次被dfs到的.] #include<iostream> #include<cstdio> #include&l ...

  8. 利用shell脚本实现nginx 的logs日志分割

    Nginx 是一个非常轻量的 Web 服务器,体积小.性能高.速度快等诸多优点.但不足的是也存在缺点,比如其产生的访问日志文件一直就是一个,不会自动地进行切割,如果访问量很大的话,将 导致日志文件容量 ...

  9. 洛谷.4655.[CEOI2017]Building Bridges(DP 斜率优化 CDQ分治)

    LOJ 洛谷 \(f_i=s_{i-1}+h_i^2+\min\{f_j-s_j+h_j^2-2h_i2h_j\}\),显然可以斜率优化. \(f_i-s_{i-1}-h_i^2+2h_ih_j=f_ ...

  10. 2017-9-13-Linux移植:u-boot的移植

    1.u-boot下载地址:http://ftp.denx.de/pub/u-boot/ 2.Linux环境下使用tar命令解压压缩包:tar -xzvf file.tar.gz tar -xvf fi ...