본문 바로가기

프로그래밍/자바 디자인 패턴

자바 디자인 패턴 튜토리얼 - 행동 디자인 패턴 - 반복자 패턴

반응형

반복자 패턴(iterator pattern)은 객체 지향 프로그래밍에서 반복자를 사용하여 컨테이너를 가로지르며 컨테이너의 요소들에 접근하는 디자인 패턴이다. 반복자 패턴은 컨테이너로부터 알고리즘을 분리시키며, 일부의 경우 알고리즘들은 필수적으로 컨테이너에 특화되어 있기 때문에 분리가 불가능하다.

이를테면, SearchForElement라는 가설적 알고리즘은 일반적으로 컨테이너에 특화된 알고리즘으로서 구현하지 않고 반복자 유형을 사용하여 구현할 수 있다. 이는 필요한 반복자 유형을 지원하는 컨테이너에 SearchForElement를 사용할 수 있게 한다.

예제

 


interface Iterator {
   public boolean hasNext();
   public Object next();
}
class LetterBag {
   public String names[] = {"R" , "J" ,"A" , "L"};
   public Iterator getIterator() {
      return new NameIterator();
   }
   class NameIterator implements Iterator {
      int index;
      @Override
      public boolean hasNext() {
         if(index < names.length){
            return true;
         }
         return false;
      }
      @Override
      public Object next() {
         if(this.hasNext()){
            return names[index++];
         }
         return null;
      }    
   }
}
public class Main {
   public static void main(String[] args) {
      LetterBag bag = new LetterBag();
      for(Iterator iter = bag.getIterator(); iter.hasNext();){
         String name = (String)iter.next();
         System.out.println("Name : " + name);
      }   
   }
}

위의 코드는 다음 결과를 출력합니다

 


Name:R
Name:J
Name:A
Name:L
반응형