迭代器模式(Iterator Pattern)
2016-11-28 14:24
351 查看
1. 迭代器模式定义
提供一种方法顺序访问一个聚合对象中各个元素,而又不需暴露该对象的内部表示。适用性:
访问一个聚合对象的内容而无需暴露它的内部表示。
支持对聚合对象的多种遍历。
为遍历不同的聚合结构提供一个统一的接口(即, 支持多态迭代)。
类图:
2. 实例
//测试 public class IteratorPatternTest { public static void main(String[] args){ Collection collection=new MyCollection(); Iterator iterator=collection.createIterator(); while(iterator.hasNext()){ String s=iterator.next().toString(); System.out.println(s); } } } //集合接口 interface Collection{ public Iterator createIterator(); public Object get(int pos); public int size(); } //集合接口的实现类 class MyCollection implements Collection{ private String str[]={"a","b","c","d","e","f"}; @Override public Iterator createIterator(){ return new MyIterator(this); } @Override public Object get(int pos){ return str[pos]; } @Override public int size(){ return str.length; } } //迭代器接口 interface Iterator{ public boolean hasNext(); public Object next(); //public void remove(); } //迭代器接口的实现类 class MyIterator implements Iterator{ private Collection collection=null; private int pos=-1; public MyIterator(Collection collection){ this.collection=collection; } @Override public boolean hasNext(){ if(pos<collection.size()-1){ return true; } return false; } @Override public Object next(){ if(hasNext()){ pos++; } return collection.get(pos); } }
运行结果:
a b c d e f
相关文章推荐
- 我所理解的设计模式(C++实现)——迭代器模式(Iterator Pattern)
- 迭代器模式(Iterator Pattern)
- 设计模式14 - 迭代器模式【Iterator Pattern】
- NET设计模式(18):迭代器模式(Iterator Pattern)(转载)
- (第Ⅳ部分 行为型模式篇) 第17章 迭代器模式(Iterator Pattern)
- 迭代器模式(Iterator pattern)
- 迭代器模式(Iterator pattern)
- .NET设计模式(18):迭代器模式(Iterator Pattern)
- 模式十:迭代器模式(Iterator Pattern)——顺序访问聚合对象元素
- 第 14 章 迭代器模式【Iterator Pattern】
- 设计模式之迭代器模式(Iterator Pattern)
- .NET设计模式(18):迭代器模式(Iterator Pattern)(转)
- 【23种设计模式】之 迭代器模式(Iterator Pattern)
- C#设计模式——迭代器模式(Iterator Pattern)
- 迭代器模式(Iterator Pattern)
- 设计模式学习总结-迭代器模式(Iterator Pattern)
- 【设计模式】迭代器模式(Iterator Pattern)
- C#设计模式(16)——迭代器模式(Iterator Pattern)
- 迭代器模式(Iterator Pattern)
- (第Ⅳ部分 行为型模式篇) 第17章 迭代器模式(Iterator Pattern)