ㅇ. 정의
복합 객체 요소들(aggregate)의 내부 표현 방식을 공개하지 않고도 순차적으로 접근할 수 있는 방법을 제공한다.
public class Client {
public static void main(String[] args) {
ArrayListAggregate newList = new ArrayListAggregate();
newList.add('a');
newList.add('c');
newList.add('b');
newList.add('d');
IIterator iterator = newList.createIterator();
Object obj = null;
while(iterator.hasNext()) {
obj = iterator.next();
System.out.println(obj);
}
LinkedListAggregate newList2 = new LinkedListAggregate();
newList2.add(1);
newList2.add(3);
newList2.add(2);
newList2.add(4);
IIterator iterator2 = newList2.createIterator();
while(iterator2.hasNext()) {
obj = iterator2.next();
System.out.println(obj);
}
--------------------------------------------------------------------
public interface IAggregate {
public IIterator createIterator();
--------------------------------------------------------------------
public class ArrayListAggregate implements IAggregate {
ArrayList arrayList = new ArrayList();
public IIterator createIterator() {
return new ArrayListIterator(this);
}
public int size() {
return this.arrayList.size();
}
public boolean add(Object obj) {
return this.arrayList.add(obj);
}
public Object get(int index) {
return this.arrayList.get(index);
}
--------------------------------------------------------------------
public class LinkedListAggregate implements IAggregate {
LinkedList linkedList = new LinkedList();
public IIterator createIterator() {
return new LinkedListIterator(this);
}
public int size() {
return this.linkedList.size();
}
public boolean add(Object obj) {
return this.linkedList.add(obj);
}
public Object get(int index) {
return this.linkedList.get(index);
}
--------------------------------------------------------------------
public interface IIterator {
abstract boolean hasNext();
abstract Object next();
--------------------------------------------------------------------
public class ArrayListIterator implements IIterator {
ArrayListAggregate aggregate = null;
int currentIndex = -1;
public ArrayListIterator(ArrayListAggregate arrayListAggregate) {
this.aggregate = arrayListAggregate;
}
public Object next() {
return this.aggregate.get(this.currentIndex);
}
public boolean hasNext() {
this.currentIndex++;
if (this.currentIndex >= this.aggregate.size() ||
this.aggregate.get(this.currentIndex) == null)
return false;
else
return true;
}
--------------------------------------------------------------------
public class LinkedListIterator implements IIterator {
LinkedListAggregate aggregate = null;
int currentIndex = -1;
public LinkedListIterator(LinkedListAggregate linkedListAggregate) {
this.aggregate = linkedListAggregate;
}
public Object next() {
return this.aggregate.get(this.currentIndex);
}
public boolean hasNext() {
this.currentIndex++;
if (this.currentIndex >= this.aggregate.size()
|| this.aggregate.get(this.currentIndex) == null)
return false;
else
return true;
}