菜鸟硕枫设计模式系列之17 迭代器模式
发布日期:2021-10-01 08:45:12
浏览次数:2
分类:技术文章
本文共 2106 字,大约阅读时间需要 7 分钟。
迭代器模式是一种行为模式。提供了一种顺序访问聚集中每个元素的办法(有可能元素之前不同类型)。迭代器在java中应用很广泛。迭代器最大的特点是提供了存储对象的聚集,另外也提供了遍历访问对象的方式。 迭代器模式类图: [img]http://dl.iteye.com/upload/attachment/364823/e347e21f-b003-3327-9c95-8e94812aee85.jpg[/img] 具体代码示例:package iteratorPattern; public class Dog { void dosomething() { System.out.println(this.getClass()+" working"); } }
package iteratorPattern; public class Child { void dosomething() { System.out.println(this.getClass()+"working"); } }
package iteratorPattern; public class Man { void dosomething() { System.out.println(this.getClass()+" working"); } }
package iteratorPattern; public class Woman{ void dosomething() { System.out.println(this.getClass()+"working"); } }对象存储集合 需要实现Iterator接口 并且有添加元素和删除元素以及遍历元素的方法
package iteratorPattern; import java.util.ArrayList; import java.util.Iterator; public class AnimalList implements Iterator{ private ArrayList测试类:
package iteratorPattern; public class IteratorTest { public static void main(String[] args){ Dog dog = new Dog(); Man man = new Man(); Woman woman = new Woman(); Child child = new Child(); AnimalList animal = new AnimalList(); animal.add(child); animal.add(man); animal.add(woman); animal.add(dog); animal.notifyThey(); } }说明: 在本例中,所有的不同类都是Object的子类,所以可以放到 animal中去,animal调用notifyThey方法遍历通知每一个存在于animal中的对象,似乎有了点订阅发布(观察者模式)中发布的影子。
转载地址:https://blog.csdn.net/iteye_2655/article/details/81970491 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月10日 01时44分20秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
PHP使用curl_multi_add_handle并行处理
2019-04-27
NP问题
2019-04-27
AT&T与Intel汇编语言的比较
2019-04-27
javascript解析json
2019-04-27
WinDbg安装与使用
2019-04-27
推荐阅读的多核编程技术书籍
2019-04-27
维基百科上的算法和数据结构链接很强大
2019-04-27
选择排序
2019-04-27
PHP session回收机制
2019-04-27
最新的全球编程语言,操作系统,web服务器等使用率分析报告
2019-04-27
用C语言写PHP扩展
2019-04-27
PHP Extension programming
2019-04-27
海量数据处理
2019-04-27
PHP防止注入攻击
2019-04-27
多路IO复用模型 select epoll 等
2019-04-27
Linux Epoll介绍和程序实例
2019-04-27
output_buffering详细介绍
2019-04-27
php缓冲 output_buffering和ob_start
2019-04-27
php error_reporting 详解
2019-04-27
剖析PHP中的输出缓冲
2019-04-27