模式定义
迭代器模式(Iterator Pattern):提供一种方法来访问聚合对象,而不用暴露这个对象的内部表示。迭代器模式是一种对象行为型模式。
模式结构
迭代器模式结构图如下所示:
Iterator
抽象迭代器定义了访问和遍历元素的接口,一般声明如下方法:用于获取第一个元素的first(),用于访问下一个元素的next(),用于判断是否还有下一个元素的hasNext(),用于获取当前元素的currentItem(),在其子类中将实现这些方法。ConcreteIterator
具体迭代器实现了抽象迭代器接口,完成对集合对象的遍历,同时在对聚合进行遍历时跟踪其当前位置。Aggregate
抽象聚合类用于存储对象,并定义创建相应迭代器对象的接口,声明一个createIterator()方法用于创建一个迭代器对象ConcreteAggregate
具体聚合类实现了创建相应迭代器的接口,实现了在聚合类中声明的createIterator()方法,并返回一个与该具体聚合相对应的具体迭代器ConcreteIterator实例
实例
电视机遥控器就是一个迭代器的实例,通过它可以实现对电视机频道集合的遍历操作,本实例将模拟电视机遥控器的实现。
实例类图如下:
public interface TVIterator {
void setChannel(int i);
void next();
void previous();
boolean isLast();
Object currentChannel();
boolean isFirst();
}
public interface Television {
TVIterator createIterator();
}
public class SkyworthTelevision implements Television {
private Object[] obj = {"CCTV-1", "CCTV-2", "CCTV-3", "CCTV-4"};
public TVIterator createIterator() {
return new SkyworthIterator();
}
private class SkyworthIterator implements TVIterator {
private int currentIndex = 0;
public void next() {
if (currentIndex < obj.length) {
currentIndex++;
}
}
public void previous() {
if (currentIndex > 0) {
currentIndex--;
}
}
public void setChannel(int i) {
if (i >= 0 && i <= obj.length) {
currentIndex = i;
}
}
public Object currentChannel() {
return obj[currentIndex];
}
public boolean isFirst() {
return currentIndex == 0;
}
public boolean isLast() {
return currentIndex == obj.length;
}
}
}
public class TCLTelevision implements Television {
private Object[] obj = {"四川电视台", "北京电视台", "河南电视台", "天津电视台"};
public TVIterator createIterator() {
return new TCLIterator();
}
private class TCLIterator implements TVIterator {
private int currentIndex = 0;
public void next() {
if (currentIndex < obj.length) {
currentIndex++;
}
}
public void previous() {
if (currentIndex > 0) {
currentIndex--;
}
}
public void setChannel(int i) {
if (i >= 0 && i <= obj.length) {
currentIndex = i;
}
}
public Object currentChannel() {
return obj[currentIndex];
}
public boolean isFirst() {
return currentIndex == 0;
}
public boolean isLast() {
return currentIndex == obj.length;
}
}
}
public class Client {
public static void display(Television tv) {
TVIterator i = tv.createIterator();
while (!i.isLast()) {
System.out.println(i.currentChannel().toString());
i.next();
}
}
public static void main(String[] args) {
Television tv = new TCLTelevision();
display(tv);
}
}