0%

迭代器模式

迭代器模式

提供一种方法顺序遍历容器对象中各个元素,而又不暴露该对象的内部细节,容器对象指数组、集合等

核心概念

  • Iterator 迭代器接口,定义next和hasNext方法
  • ConcreteIterator 具体的迭代器实现
  • Collection 容器接口,定义iterator方法来创建Iterator对象
  • ConcreteCollection 容器实现类,创建具体的迭代器对象ConcreteIterator
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* 迭代器接口
* @author zh
* @date 2022/10/14 14:41
*/
public interface Iterator<E> {

// 移动到第一个位置
void first();

// 返回当前元素,并移动到下一个位置
E next();

// 是否是最后一个元素
boolean hasNext();

}

public class ConcreteIterator<E> implements Iterator<E>{

private ConcreteCollection<E> collection;

// 记录当前索引位置
private int index = 0;

public ConcreteIterator(ConcreteCollection<E> collection){
this.collection = collection;
}

@Override
public void first() {
index = 0;
}

@Override
public E next() {
int i = index;
if(hasNext()){
index = i+1;
return collection.get(i);
}

return null;

}

@Override
public boolean hasNext() {
if(index == collection.size()){
return false;
}
return true;
}
}

/**
* 容器接口
* @author zh
* @date 2022/10/14 14:44
*/
public interface Collection<E> {
// 获取迭代器
Iterator<E> iterator();
}

/**
* @author zh
* @date 2022/10/14 14:45
*/
public class ConcreteCollection<E> implements Collection<E>{

// 元素
private E[] arrays;

public ConcreteCollection(E[] arrays){
this.arrays = arrays;
}

@Override
public Iterator<E> iterator() {
// 实例化迭代器
return new ConcreteIterator<>(this);
}

// 根据索引位置获取元素
public E get(int index){
E ele = null;
if(index < arrays.length){
ele = arrays[index];
}
return ele;
}

public int size(){
return arrays.length;
}
}

优缺点

优点

  • 更好的封装性,简化了容器的接口

缺点

欢迎关注我的其它发布渠道