Iterator



어떠한 종류의 데이터 집합이 있다. 이 데이터를 조작, 검색 등을 하는 기능이 포함 되어있다. 이 중 검색 기능과 다른 기능이 뒤섞여 개발하면 클래스간의 결합도가 증가되어 코드가 보기가 어려워진다. Iterator 패턴을 이용해 검색 기능을 재사용 가능 하게 만들어 보자.


 

검색 기능을 재사용 하는 Iterator



Dvd 대여점이 있다. 이 대여점에 신작 Dvd가 추가되고 모든 Dvd를 데이터를 출력하는 것을 만들어 보겠다.



 이름

 해설

 Aggregate

 집합체를 나타내는 인터페이스 

 Iterator

 검색 실행하는 인터페이스 

 Dvd

 Dvd를 나타내는 클래스

 DvdStore

 Dvd 대여점을 나타내는 클래스 

 DvdStoreIterator

 Dvd 대여점을 검색하는 클래스 

 Main

 프로그램 시작 클래스 


[Aggregate]

public interface Aggregate {

public Iterator iterator();

}


[Iterator]

public interface Iterator {

public boolean hasNext();

public Object next();

}


[Dvd]

public class Dvd {

private String name;

public Dvd(String name) {

this.name = name;

}

public String getName() {

return name;

}

}


[DvdStore]

public class DvdStore implements Aggregate {

private Dvd[] Dvds;

private int last = 0;

public DvdStore(int maxsize) {

Dvds = new Dvd[maxsize];

}

public Dvd getDvdAt(int index) {

return Dvds[index];

}

public void appendDvd(Dvd dvd) {

Dvds[last] = dvd;

last++;

}

public int getLength() {

return last;

}

public Iterator iterator() {

return new DvdStoreIterator(this);

}

}


[DvdStoreIterator]

public class DvdStoreIterator implements Iterator{

private DvdStore dvdStore;

private int index;

public DvdStoreIterator( DvdStore dvdStore ) {

this.dvdStore = dvdStore;

index = 0;

}

public boolean hasNext() {

if ( index < dvdStore.getLength() )

return true;

else

return false;

}

public Object next() {

Dvd dvd = dvdStore.getDvdAt(index);

index++;

return dvd;

}

}


[Main]

public class Main {

public static void main(String[] args) {

DvdStore dvdStore = new DvdStore(5);

dvdStore.appendDvd(new Dvd("바람과 함께 사라지다."));

dvdStore.appendDvd(new Dvd("살인의 추억"));

dvdStore.appendDvd(new Dvd("바닷마을 다이어리"));

dvdStore.appendDvd(new Dvd("어벤져스"));

dvdStore.appendDvd(new Dvd("터미네이터"));


Iterator it = dvdStore.iterator();

while( it.hasNext() ) {

Dvd dvd = (Dvd)it.next();

System.out.println(dvd.getName());

}

}

}


이러한 복잡한 패턴을 왜 쓰냐고 반문 할 수 있을지 모른다.  이렇게 Iterator 검색 기능을 따로 분리 하지 않는다면 for문을 돌면서 배열로 검색해도 된다. 하지만 배열이 아닌 Vector나 다른 자료형으로 바뀌면 어떻게 되는가? 아마 처음부터 다시 프로그램 해야 될 것이다.  DvdStore에 배열로 되어 있는 부분을 Vector로 고쳐보면 다른 부분을 모두 재사용이 가능 할 것이다.


반응형

+ Recent posts