mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-31 19:13:42 +00:00
Update 设计模式 - 迭代器.md
调整示例代码泛型,补充运行输出及客户端解耦说明,文字校对参考书籍格式;重新绘制 dp-iterator.png 配图。
This commit is contained in:
Binary file not shown.
|
Before Width: | Height: | Size: 170 KiB After Width: | Height: | Size: 173 KiB |
+18
-9
@@ -12,13 +12,13 @@
|
||||
|
||||
### 实现
|
||||
```java
|
||||
public interface Aggregate {
|
||||
Iterator createIterator();
|
||||
public interface Aggregate<Item> {
|
||||
Iterator<Item> createIterator();
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class ConcreteAggregate implements Aggregate {
|
||||
public class ConcreteAggregate implements Aggregate<Integer> {
|
||||
|
||||
private Integer[] items;
|
||||
|
||||
@@ -30,8 +30,8 @@ public class ConcreteAggregate implements Aggregate {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator createIterator() {
|
||||
return new ConcreteIterator<Integer>(items);
|
||||
public Iterator<Integer> createIterator() {
|
||||
return new ConcreteIterator<>(items);
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -46,7 +46,7 @@ public interface Iterator<Item> {
|
||||
```
|
||||
|
||||
```java
|
||||
public class ConcreteIterator<Item> implements Iterator {
|
||||
public class ConcreteIterator<Item> implements Iterator<Item> {
|
||||
|
||||
private Item[] items;
|
||||
private int position = 0;
|
||||
@@ -56,7 +56,7 @@ public class ConcreteIterator<Item> implements Iterator {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object next() {
|
||||
public Item next() {
|
||||
return items[position++];
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ public class ConcreteIterator<Item> implements Iterator {
|
||||
public class Client {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Aggregate aggregate = new ConcreteAggregate();
|
||||
Aggregate<Integer> aggregate = new ConcreteAggregate();
|
||||
Iterator<Integer> iterator = aggregate.createIterator();
|
||||
while (iterator.hasNext()) {
|
||||
System.out.println(iterator.next());
|
||||
@@ -80,6 +80,15 @@ public class Client {
|
||||
}
|
||||
```
|
||||
|
||||
```text
|
||||
0
|
||||
1
|
||||
...
|
||||
9
|
||||
```
|
||||
|
||||
Client 只用到 hasNext() 和 next(),ConcreteAggregate 把数组换成链表时,只要同时换掉迭代器,Client 不用改。
|
||||
|
||||
### JDK 中的应用
|
||||
- [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)
|
||||
- [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html)
|
||||
@@ -87,4 +96,4 @@ public class Client {
|
||||
## 参考资料
|
||||
|
||||
- 弗里曼. Head First 设计模式 [M]. 中国电力出版社, 2007.
|
||||
- Gamma E. 设计模式: 可复用面向对象软件的基础 [M]. 机械工业出版社, 2007.
|
||||
- Gamma E. 设计模式:可复用面向对象软件的基础 [M]. 机械工业出版社, 2007.
|
||||
|
||||
Reference in New Issue
Block a user