개요
디자인 패턴을 따로 학습하지 않았어도 Collection을 사용하면서 자연스럽게 Iterator를 사용해본 경우가 많을 것이다.
배열이나 Collection 같은 집합체를 다루는데 있어서 집합체 객체 자체를 가지고 반복작업을 하지 않고 Iterator를 사용해서 얻을 수 있는 이득은 무엇일까? 바로 집합체 구현과 반복작업을 분리할 수 있다는 점이다. 이 말의 의미를 아래 예제로 살펴본다.
역할
먼저 Iterator 패턴에서는 아래의 Role이 필요하다.
Aggregate(집합체)
interface(추상 클래스)로 추상화되어있는 집합체로 Iterator와의 인터페이스 역할을 한다.
Iterator(반복자)
interface(추상 클래스)로 반복자를 호출할 때 인터페이스 역할을 한다.
ConreteAggregate(구체적 집합체)
집합체를 실제로 구현한다. 예제에서는 BookShelf 클래스이다.
ConcreteIterator(구체적 반복자)
반복자를 실제로 구현한다. 예제에서는 BookShelfIterator 크래스이다.
이득 및 유의사항
Aggregate와 Iterator interface를 사용하는 이유는 구체적 집합체나 구체적 반복자를 여러개 생성하더라도 동일한 인터페이스를 제공하기 위함이다. 예를 들어 Collection에서 여러 종류의 Set 클래스가 존재해도 모두 동일한 iterator() 메소드를 갖는 것과 같은 이유이다.
예제 코드
public interface Aggregate {
public abstract Iterator iterator();
}
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
//ConcreteAggregate역할을 BookShelf가 한다. Book은 그냥 임의의 참조형 데이터 타입
public class BookShelf implements Aggregate{
private Book[] books;
private int last = 0;
public BookShelf(int maxsize) {
this.books = new Book[maxsize];
}
public Book getBookAt(int index) {
return books[index];
}
public void appendBook(Book book) {
this.books[last] = book;
last++;
}
public int getLength() {
return last;
}
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
//ConcreteIterator역할을 BookShelfIterator 클래스가 한다.
public class BookShelfIterator implements Iterator{
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
this.index = 0;
}
public boolean hasNext() {
return index < bookShelf.getLength() ? true : false;
}
public Object next() {
Book book = bookShelf.getBookAt(index++);
return book;
}
}
'디자인 패턴' 카테고리의 다른 글
5. Singleton 패턴 (0) | 2020.12.02 |
---|---|
4. FactoryMethod 패턴 (0) | 2020.12.01 |
3. Template Method 패턴 (0) | 2020.11.30 |
2. Adapter 패턴 (0) | 2020.11.29 |
0.디자인 패턴이란? (0) | 2020.11.27 |