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. 使用 Django-debug-toolbar 优化Query 提高代码效率

    一段程序执行效率慢,除了cpu计算耗时外,还有一个很重要的原因是SQL的Duplicated过多,使用Django-debug-toolbar能够快速找出哪些地方的SQL可以优化,提高程序执行效率 1 ...

  2. scrapy 日志一般配置

  3. Idea问题:“marketplace plugins are not loaded”解决方案

    博主本人遇见该问题时是想要通过Idea的plugins工具下载阿里巴巴的代码规约工具 但是在我点开settings,然后打开plugins工具时竟然给我提示“marketplace plugins a ...

  4. goLand工程结构管理

    goLand工程结构管理  转 https://www.jianshu.com/p/eb7b1fd7179e 开始之前请确保安装好了 go语言环境并配置好了gopath环境变量 1.创建一个新目录并打 ...

  5. type__列表

  6. React-Native + Genymotion android开发环境搭建

    1.解压android-sdk_r24.3.4-windows.zip放到一个空间大的开发盘中 2.添加环境变量,路径时 ANDROID_HOME D:\Android\android-sdk-win ...

  7. MySQL 查询所有的表名

    select table_name from information_schema.tables where table_schema='laiu8' and table_type='base tab ...

  8. 深度学习目标检测:RCNN,Fast,Faster,YOLO,SSD比较

    转载出处:http://blog.csdn.net/ikerpeng/article/details/54316814 知乎的图可以放大,更清晰,链接:https://www.zhihu.com/qu ...

  9. linux上如何自动获取ip及连接互联网

    1.讲与虚拟机连接网卡设置为net连接 2.BOOTPROTO=dhcp 3.注释原来的ip 4.最后一句网关注释 5.重启网卡 service network restart

  10. DJI-A2调参详细教程

    DJI-A2飞控系统用户手册 https://wenku.baidu.com/view/bb632f88227916888586d749.html DJI-A2调参软件视频教程 http://www. ...