auto commit
This commit is contained in:
parent
b0ba55fa31
commit
ddd10c1aa8
|
@ -496,7 +496,80 @@ public class Client {
|
|||
|
||||
### 意图
|
||||
|
||||
提供一种一致的访问聚合对象元素的方法,并且不暴露聚合对象的内部表示。
|
||||
提供一种顺序访问聚合对象元素的方法,并且不暴露聚合对象的内部表示。
|
||||
|
||||
### 类图
|
||||
|
||||
<div align="center"> <img src="../pics//b0f61ac2-a4b6-4042-9cf0-ccf4238c1ff7.png"/> </div><br>
|
||||
|
||||
### 实现
|
||||
|
||||
```java
|
||||
public interface Aggregate {
|
||||
Iterator createIterator();
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class ConcreteAggregate implements Aggregate {
|
||||
|
||||
private Integer[] items;
|
||||
|
||||
public ConcreteAggregate() {
|
||||
items = new Integer[10];
|
||||
for (int i = 0; i < items.length; i++) {
|
||||
items[i] = i;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator createIterator() {
|
||||
return new ConcreteIterator<Integer>(items);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public interface Iterator<Item> {
|
||||
Item next();
|
||||
|
||||
boolean hasNext();
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class ConcreteIterator<Item> implements Iterator {
|
||||
|
||||
private Item[] items;
|
||||
private int position = 0;
|
||||
|
||||
public ConcreteIterator(Item[] items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object next() {
|
||||
return items[position++];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return position < items.length;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class Client {
|
||||
public static void main(String[] args) {
|
||||
Aggregate aggregate = new ConcreteAggregate();
|
||||
Iterator<Integer> iterator = aggregate.createIterator();
|
||||
while (iterator.hasNext()) {
|
||||
System.out.println(iterator.next());
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### JDK
|
||||
|
||||
|
|
BIN
pics/b0f61ac2-a4b6-4042-9cf0-ccf4238c1ff7.png
Normal file
BIN
pics/b0f61ac2-a4b6-4042-9cf0-ccf4238c1ff7.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 18 KiB |
Loading…
Reference in New Issue
Block a user