设计模式(16)-迭代器模式(Iterator)
来源:互联网 发布:c语言强制类型转换规则 编辑:程序博客网 时间:2024/05/21 11:13
设计模式(15)-观察者模式(Observer)
16、迭代器模式(Iterator)
顾名思义,迭代器模式就是顺序访问聚集中的对象,一般来说,集合中非常常见,如果对集合类比较熟悉的话,理解本模式会十分轻松。
例子:
public interface Collection { public Iterator iterator(); /*取得集合元素*/ public Object get(int i); /*取得集合大小*/ public int size(); }
public interface Iterator { //前移 上一个元素 public Object previous(); //后移 下一个元素 public Object next(); public boolean hasNext(); //取得第一个元素 public Object first(); }
public class MyCollection implements Collection { //假设这个集合内部是由数组实现 public String string[] = {"A","B","C","D","E"}; public Iterator iterator() { return new MyIterator(this); } public Object get(int i) { return string[i]; } public int size() { return string.length; } }
//这个地方其实一般会设计为内部类 public class MyIterator implements Iterator { private Collection collection; private int pos = -1; public MyIterator(Collection collection){ this.collection = collection; } public Object previous() { if(pos > 0){ pos--; } return collection.get(pos); } public Object next() { if(pos<collection.size()-1){ pos++; } return collection.get(pos); } public boolean hasNext() { if(pos<collection.size()-1){ return true; }else{ return false; } } public Object first() { pos = 0; return collection.get(pos); } }
//测试类 public class Test { public static void main(String[] args) { Collection collection = new MyCollection(); Iterator it = collection.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } }
0 0
- 设计模式(16)-迭代器模式(Iterator)
- 设计模式16 - Iterator 迭代器模式
- 设计模式--迭代器模式(Iterator)
- 设计模式之--迭代器模式(Iterator)
- java设计模式-迭代器模式(Iterator)
- 设计模式之(Iterator)迭代器模式
- java设计模式-迭代器模式(Iterator)
- 设计模式:迭代器模式(Iterator)
- 设计模式:迭代器模式(Iterator)
- [设计模式]迭代器模式(Iterator)
- 【设计模式】迭代器模式(Iterator Pattern)
- 设计模式(16)——迭代器模式(Iterator Pattern)
- 【设计模式 - 16】之迭代器模式(Iterator)
- 设计模式 -- Iterator(迭代器)
- Iterator(迭代器)设计模式
- Iterator 迭代器设计模式
- Iterator 迭代器设计模式
- 设计模式----Iterator(迭代器)模式
- 慕课网实现自定义多指触控双击缩放的IamgeView以及解决和ViewPager的滑动冲突代码摘要
- Ceph分布式存储系统
- Codeforces Round #364 (Div. 1) C. Break Up (桥)
- 动态规划问题系列---word break问题
- 设计模式(15)-观察者模式(Observer)
- 设计模式(16)-迭代器模式(Iterator)
- 猫猫学IOS(三十一)UI之Quartz2D图形上下文栈
- 丫头还是别做程序猿了。。。
- 猫猫学IOS(三十三)UI之Quartz2D雪花飘落效果刷帧
- 用Qt Creator编写一个简单的窗口程序
- Leetcode #3 Longest Substring Without Repeating Characters
- Unity3D中函数执行顺序
- 不会排序的司机不是好司机——八大排序算法
- 面向对象 重中之重