본문 바로가기
역량 UP!/DesignPattern

[DesignPattern] Iterator pattern

by 태하팍 2014. 1. 6.
반응형


Iterator Pattern


 개요

 예제(Java)

 같이보기

 참고 사항


<< 개요 >>

Iterator Pattern -  하나씩 열거하면서 처리 한다.

 

 


<< 예제(Java) >>

1. 결과 

실용주의 프로그래머
애자일 프로젝트
파워 스피치
왜 일하는가?


2. 테스트 코드 

 package kr.pe.acet.iterator;

 

public class AggregateTest {
    @org.junit.Test
    public void testIterator() throws Exception {
        BookShelf bookShelf = new BookShelf(4);

        bookShelf.appendBook(new Book("실용주의 프로그래머"));
        bookShelf.appendBook(new Book("애자일 프로젝트"));
        bookShelf.appendBook(new Book("파워 스피치"));
        bookShelf.appendBook(new Book("왜 일하는가?"));

        Iterator it = bookShelf.iterator();

        while(it.hasNext()){
            Book book = (Book)it.next();

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

}

 

3.Aggregate  

      package kr.pe.acet.iterator;

import java.util.Iterator;

public interface Aggregate {
    public abstract kr.pe.acet.iterator.Iterator iterator();
}

4. BookShelf 

 package kr.pe.acet.iterator;


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;
    }
    @Override
    public Iterator iterator() {
        // TODO Auto-generated method stub
        return new BookShelfIterator(this);
    }
}

 

5. BookShelfIterator 

 package kr.pe.acet.iterator;

public class BookShelfIterator implements Iterator{
    private BookShelf bookShelf;

    private int index;

    public BookShelfIterator(BookShelf bookShelf){
        this.bookShelf = bookShelf;
        this.index = 0;
    }

    public boolean hasNext(){
        if(index < bookShelf.getLength()){
            return true;
        }else{
            return false;
        }
    }
    public Object next(){

        Book book = bookShelf.getBookAt(index);
        index++;
        return book;
    }
}

 

6. Iterator 

package kr.pe.acet.iterator;

public interface Iterator {
    public abstract boolean hasNext();
    public abstract Object next();
}

 

 

<< 같이 보기 >>

1. Visitor pattern

2. Composite pattern

3. Factory Method pattern


<< 참고 사항 >>

1.Java 언어로 배우는 디자인 패턴 입문



반응형