거꾸로 바라본 세상
article thumbnail
반응형

Iterator Pattern


- 어떤 하나의 집합의 정보를 하나 씩 호출하여 전체를 순차적(차례대로)으로 검색하여 처리하는 방법으로 Iterator은 무언가를 '반복하다'라는 의미이다.




<Iterator 패턴의 다이어그램>




1. Iterator 인터페이스


- Iterator 인터페이스는 요소를 하나씩 나열하여 루프 변수같은 역할을 수행한다. 

쉽게말하면 순서대로 검색하기위한 인터페이스다. 


Iterator 내의 메소드는 2개 이다.


public interface Iterator<E> {

boolean hasNext();

E next();

}


hasNext() : 다음요소가 있는지 검사하는 메서드이다. 

- 다음 요소가 존재한다면 hasNext 반환 값이 true가 되어 조건을 수행하게 되고 false 라면 수행을 멈춘다.


next() : 다음요소의 데이터를 얻기 위한 next() 메서드이다.

- next()메서드를 호출하면 현재 위치의정보를 가져오고 다음 위치를 반환한다.



2. Aggregate 인터페이스


- Aggregate 인터페이스는 요소들이 나열되어 있는 '집합체'를 나타낸다. 이 인터페이스에 선언되어 있는 메소드는 iterator 메소드 하나 뿐이다. 이 메소드는 집합체에 대응하는 Iterator 하나를 작성하기 위한 것이다.


public interface Aggregate<E> {

public Iterator<E> iterator();

}



3. ConcreteIterator 클래스


- Iterator 인터페이스의 추상메서드를 실제로 구현하는 클래스로 내가 가지고 있는 요소를 순서대로 검색해주는 역할을 만드는 클래스이다.

(ConcreteIterator 클래스의 이름은 바꿀수있다) 


public class BookShelfIterator<E> implements Iterator<E>{

BookShelf<E> bookShelf;

int index;

public BookShelfIterator(BookShelf<E> bookShelf) {

this.bookShelf = bookShelf;

this.index =0;

}

@Override

public boolean hasNext() {

if(bookShelf.getLength()>index) {

return true;

}

else {

return false;

}

}

@Override

public E next() {

E data = (E) bookShelf.getBookAt(index);

index++;

return data;

}

}


4. ConcreteAggregate 클래스


- Aggregate의 역할을 결정한 인터페이스를 실제로 구현하는 부분이다. 구체적인 Iterator 역할. 즉 ConcreteIterator 역할의 인터페이스를 만들어내는 것이다.

(concreteAggregate 클래스의 이름은 바뀐다) 



public class BookShelf<E> implements Aggregate<E> {

private List<Book> list;

private int last = 0;

public BookShelf () {

list = new ArrayList<>();

}

public Book getBookAt(int index) {

return list.get(index);

}

public void appendBook(Book book) {

list.add(book);

}

public int getLength() {

return list.size();

}

public Iterator<E> iterator() {

return new BookShelfIterator<E>(this);

}

}





예제


Book.java

public class Book {

private String name;

public Book(String name) {

this.name = name;

}

public String getName() {

return name;

}

}



public class Main {

public static void main(String[] args) {

BookShelf<Book> bookShelf = new BookShelf<>();

bookShelf.appendBook(new Book("톰과 제러"));

bookShelf.appendBook(new Book("아파치"));

bookShelf.appendBook(new Book("스타워즈"));

bookShelf.appendBook(new Book("진주만"));

bookShelf.appendBook(new Book("전우치"));

Iterator<Book> it =bookShelf.iterator();

while(it.hasNext()) {

Book book = it.next();

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

}

}

}


반응형

'Software Engineering > Design Pattern' 카테고리의 다른 글

Observer Pattern(관찰자 패턴)  (0) 2023.04.20
Template Method Pattern(템플릿 메서드 패턴)  (0) 2016.04.26
Adapter Pattern  (0) 2016.04.25
Singleton Pattern  (0) 2016.01.31
profile

거꾸로 바라본 세상

@란지에。

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!