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();
剩下的代码不用改动一行就能编译,而且功能不变,这就是针对抽象编程的原则:对具体类的依赖性最小。
本文介绍了迭代器模式在集合类中的应用,通过此模式可以实现集合的遍历而无需暴露其内部结构。文中提供了使用不同集合类(如ArrayList、LinkedList、Vector)的示例,展示了如何在不修改原有代码的情况下轻松替换集合类型。
1077

被折叠的 条评论
为什么被折叠?



