Iterator模式
解释
多态的一个应用,各自的实现类实现自己的遍历方法,实现自己的遍历逻辑。
类图
举例学习
建立一个容器,可以存放数据,多种数据结构。
遍历时怎么遍历?
各自的数据结构实现自己的遍历方法。
代码
顶级接口
public interface Collection_<E> {
void add(E o);
int size();
Iterator_ iterator();
}
ArrayList实现
class ArrayList_<E> implements Collection_<E> {
E[] objects = (E[]) new Object[10];
private int index = 0;
public void add(E o) {
if (index == objects.length) {
E[] newObjects = (E[]) new Object[objects.length * 2];
System.arraycopy(objects, 0, newObjects, 0, objects.length);
objects = newObjects;
}
objects[index] = o;
index++;
}
public int size() {
return index;
}
@Override
public Iterator_<E> iterator() {
return new ArrayListIterator();
}
private class ArrayListIterator<E> implements Iterator_<E> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
if (currentIndex >= index) return false;
return true;
}
@Override
public E next() {
E o = (E) objects[currentIndex];
currentIndex++;
return o;
}
}
}
LinkedList实现
class LinkedList_<E> implements Collection_<E> {
Node head = null;
Node tail = null;
private int size = 0;
@Override
public void add(E o) {
Node n = new Node(o);
n.next = null;
if (head == null) {
head = n;
tail = n;
}
tail.next = n;
tail = n;
size++;
}
private static class Node<E> {
private E o;
Node next;
public Node(E o) {
this.o = o;
}
}
@Override
public int size() {
return size;
}
@Override
public Iterator_<E> iterator() {
return new LinkedListIterator();
}
private class LinkedListIterator<E> implements Iterator_<E> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
if (currentIndex < size) {
return true;
}
return false;
}
@Override
public E next() {
if (currentIndex == 0) {
currentIndex++;
return (E) head.o;
}
if (currentIndex == size) {
currentIndex++;
return (E) tail.o;
}
currentIndex++;
return getNext();
}
private E getNext() {
Node<E> result = head;
for (int i = 0; i < this.currentIndex - 1; i++) {
result = result.next;
}
return result.o;
}
}
}
测试方法
public class Main {
public static void main(String[] args) {
Collection_<String> list = new LinkedList_<>();
for(int i=0; i<15; i++) {
list.add(new String("s" + i));
}
System.out.println(list.size());
Iterator_<String> it = list.iterator();
while(it.hasNext()) {
String o = it.next();
System.out.println(o);
}
}
}
知识整理
存储数据
物理上只有两种结构
逻辑上可以有多种结构
- 举个例子:二叉树就是个逻辑结构,物理上可以使用数组也可以使用链表实现。
|