一.内容说明
某商品管理系统的商品名称存储在一个字符串数组中,现需要自定义一个双向迭代器(MyIterator)实现对该商品名称数组的双向(前向和后向)遍历。绘制类图并编程实现。
二.设计类图
三.全部类代码
//抽象迭代器类:
package iteratorpattern;
public interface Iterator {
public boolean hasNext();
public Object Next();
};
//具体迭代器类:
public class MyIterator implements Iterator{
int index;
public boolean hasNext(){
if(index < names.length){
return true;
}
return false;
}
public Object Next(){
if(this.hasNext()){
return names[index++];
}
return null;
}
}
public class MyIterator2 implements Iterator{
int flag = names.length-1;
public boolean hasNext(){
if(flag>-1){
return true;
}
return false;
}
public Object Next(){
if(this.hasNext()){
return names[flag--];
}
return null;
}
}
//抽象聚合类:
package iteratorpattern;
public interface GoodsStore {
public Iterator getMyIterator();
}
//具体聚合类:
public class MyGoodsStore implements GoodsStore{
public String names[]={"铅笔","钢笔","圆珠笔","水彩笔","毛笔","圆规","橡皮"};
public Iterator getMyIterator(){
return new MyIterator();
}
public Iterator getMyIterator2(){
return new MyIterator2();
}
}
//客户类:
package iteratorpattern;
public class Client {
public static void main(String[] args) {
MyGoodsStore mygoodsstore = new MyGoodsStore();
System.out.println("向后遍历:");
for(Iterator ite = mygoodsstore.getMyIterator();ite.hasNext();){
String name = (String)ite.Next();
System.out.println(""+name);
}
System.out.println("*******");
System.out.println("向前遍历:");
for(Iterator ite = mygoodsstore.getMyIterator2();ite.hasNext();){
String name = (String)ite.Next();
System.out.println(""+name);
}
}
}
四.运行结果
五.分析和总结
1.整体构造:
迭代器模式是针对集合对象而生的,对于集合对象而言,肯定会涉及到对集合的添加和删除操作,同时也肯定支持遍历集合元素的操作,我们此时可以把遍历操作放在集合对象中,但这样的话,集合对象既承担太多的责任了,面向对象设计原则中有一条就是单一职责原则,所有我们要尽可能地分离这些职责,用不同的类取承担不同的责任,迭代器模式就是用迭代器类来承担遍历集合的职责。
2.优点:
(1) 迭代器模式使得访问一个聚合对象的内容而无需暴露它的内部表示,即迭代抽象。
(2)迭代器模式为遍历不同的集合结构提供了一个统一的接口,从而支持同样的算法在不同的集合结构上进行操作。
3.缺点:
迭代器模式在遍历的同时更改迭代器所在的集合结构会导致出现异常。所以使用foreach语句只能在对集合进行遍历,不能在遍历的同时更改集合中的元素。