迭代器模式
迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示
类图

Iterator是迭代器的接口。
Aggregate 是创建迭代器的接口,所有想使用迭代器遍历内部元素的类,都需要实现它来创建迭代器。
ConcreateAggregate是一个集合类,希望可以通过迭代器来遍历内部元素
ConcreateAggregate 实现了 Aggregate 接口,来创建 ConcreateIterator 迭代器
ConcreateAggregate 建立内部类 ConcreateIterator来实现 Iterator的相关接口
组合模式
组合模式允许你将对象组合成树形结构来表现 “整体/部分” 层次结构。组合能让客户以一致的方式处理个别对象以及对象组合
类图

// TODO
要点:
- 迭代器允许访问聚合的元素,而不需要暴露它的内部结构
- 迭代器将遍历聚合的工作封装进一个对象中
- 当使用迭代器的时候,我们依赖聚合提供遍历
- 迭代器提供了一个通用的接口,让我们遍历聚合的项,当我们编码使用聚合的项时,就可以使用多态机制
- 我们应该努力让一个类只分配一个责任
- 组合模式提供一个结构,可同时包容个别对象和组合对象
- 组合模式允许客户对个别对象已经组合对象一视同仁
- 组合结构内的任意对象称为组件,组件可以是组合,也可以是叶子节点
- 在实现组合模式时,有许多设计上的折中。你要根据需要平衡透明性和安全性
策略——封装可以互换的行为,并使用委托决定使用哪一个
适配器——改变一个或多个类的接口
外观——简化一群类的接口
观察者——当某个状态改变时,允许一群对象能被通知到
迭代器——提供一个方式来遍历集合,而无需暴露集合的实现
组合——客户可以将对象的集合以及个别的对象一视同仁
迭代器例子
使用迭代器模式来遍历集合和数组
首先建立迭代器接口,和返回迭代器的Container 接口1
2
3
4
5
6
7
8public interface Iterator{
boolean hasNext();
Object next();
}
public interface Container {
public Iterator getIterator();
}
然后自定义一个聚集类,内部使用数组实现1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27public class NameRepository implements Container {
public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};
public Iterator getIterator() {
return new NameIterator();
}
private class NameIterator 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;
}
}
}
使用迭代器遍历聚集类1
2
3
4
5
6
7
8
9
10
11public class IteratorPatternDemo {
public static void main(String[] args) {
NameRepository namesRepository = new NameRepository();
Iterator iter = namesRepository.getIterator();
while (iter.hasNext()){
String name = (String)iter.next();
System.out.println("Name : " + name);
}
}
}