1. 迭代器模式
1.1 迭代器模式简介
遍历一个聚合对象,又不需要了解聚合对象的内部结构,可以使用迭代器模式。
特点:
- 主要用于描述对类或对象怎样交互和怎样分配职责;
- 提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
- 访问一个聚合对象的内容而无需暴露它的内部表示。
- 支持对聚合对象的多个和多种遍历。
- 为遍历不同的聚合结构提供一个统一的接口
1.2 迭代器模式组成
UML图:
主要角色:
- Iterator: 抽象迭代器
- ConcreteIterator: 具体迭代器
- Aggregate: 抽象聚合类
- ConcreteAggregate: 具体聚合类
2. 迭代器实现示例
Iterator:
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
Aggregate:
public interface Aggregate {
public abstract Iterator iterator();
}
Television:
public class Television implements Aggregate {
private Channel[] channels;
private int last = 0;
public Television(int maxsize) {
this.channels = new Channel[maxsize];
}
public Channel getChannelAt(int index) {
return Channels[index];
}
public void appendChannel(Channel Channel) {
this.Channels[last] = Channel;
last++;
}
public int getLength(){
return last;
}
@Override
public Iterator iterator() {
return new ChannelIterator(this);
}
}
ChannelIterator:
public class TelevisionIterator implements Iterator {
private Television television;
private int index;
public TelevisionIterator(Television television) {
this.Television = television;
this.index = 0;
}
@Override
public boolean hasNext() {
if (index < television.getLength()) {
return true;
}
return false;
}
@Override
public Object next() {
Channel channel = television.getChannelAt(index);
index ++;
return channel;
}
}
使用示例:
Television television = new Television(4);
television.appendChannel(new Channel("cctv-1"));
television.appendChannel(new Channel("cctv-4"));
television.appendChannel(new Channel("cctv-6"));
television.appendChannel(new Channel("cctv-8"));
Iterator it = television.iterator();
while (it.hasNext()) {
Channel channel = (Channel) it.next();
System.out.println(channel.getName());
}
网友评论