Iterator模式是用于遍历集合类的标准访问方法。
它可以把访问逻辑从不同类型的集合类中抽象出来,
从而避免向客户端暴露集合的内部结构
完整示例
Collection c = new ArrayList();
c.add("abc");
c.add("xyz");
for(Iterator it = c.iterator(); it.hasNext(); ) {
String s = (String)it.next();
System.out.println(s);
}
不需要关注客户的内部结构
例如将Collection c = new ArrayList();
改为Collection c = new LinkedList();
改为Collection c = new Vector();
剩下的代码不用改动一行就能编译,而且功能不变,这就是针对抽象编程的原则:对具体类的依赖性最小。
它可以把访问逻辑从不同类型的集合类中抽象出来,
从而避免向客户端暴露集合的内部结构
完整示例
Collection c = new ArrayList();
c.add("abc");
c.add("xyz");
for(Iterator it = c.iterator(); it.hasNext(); ) {
String s = (String)it.next();
System.out.println(s);
}
不需要关注客户的内部结构
例如将Collection c = new ArrayList();
改为Collection c = new LinkedList();
改为Collection c = new Vector();
剩下的代码不用改动一行就能编译,而且功能不变,这就是针对抽象编程的原则:对具体类的依赖性最小。