@ 기본 패턴
- Iterator(반복자) : interface Iterator
package basic.pattern;
public interface Iterator {
public abstract Object next();
public abstract boolean hasNext();
}
- Aggregate(집합체) : interface Aggregate
package basic.pattern;
public interface Aggregate {
public abstract Iterator iterator();
public abstract int getLength();
public abstract Object getBookAt(int index);
}
@ 구현
- Element(요소) : Book
package Sample2;
public class Book {
String name;
public Book(String name) {
this.name = name;
}
String getName(){
return name;
}
}
- ConcreteAggregate(구체적인 집합체)
1. BookShelfArrange.java
package Sample2;
import basic.pattern.Aggregate;
import basic.pattern.Iterator;
public class BookShelfArrange implements Aggregate {
private Book[] books;
private int last=0;
public BookShelfArrange(int max) {
books=new Book[max];
}
public void appendBook(Book book){
this.books[last]=book;
last++;
}
public Book getBookAt(int index){
return books[index];
}
public int getLength(){
return last;
}
public Iterator iterator() {
// TODO Auto-generated method stub
return new BookShelfBackIterator(this);
}
}
2. BookShelfList
package Sample2;
import java.util.ArrayList;
import basic.pattern.Aggregate;
import basic.pattern.Iterator;
public class BookShelfList implements Aggregate {
private ArrayList<Book> books;
private int last=0;
public BookShelfList() {
books=new ArrayList<Book>();
}
public void appendBook(Book book){
books.add(book);
last++;
}
public Book getBookAt(int index){
return books.get(index);
}
public int getLength(){
return last;
}
public Iterator iterator() {
// TODO Auto-generated method stub
return new BookShelfBackIterator(this);
}
}
- ConcreteIterator(구체적인 반복자)
1. BookShelfBackIterator
package Sample2;
import basic.pattern.Aggregate;
import basic.pattern.Iterator;
public class BookShelfBackIterator implements Iterator {
private Aggregate bookShelf;
private int index;
public BookShelfBackIterator(Aggregate shelf) {
this.bookShelf = shelf;
index=0;
}
@Override
public Object next() {
Book book=(Book)bookShelf.getBookAt(index);
index++;
return book;
}
@Override
public boolean hasNext() {
if(index<bookShelf.getLength())
return true;
else
return false;
}
}
@ 실행
- Main
package Sample2;
import basic.pattern.Iterator;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// BookShelfList bookShelf=new BookShelfList();
BookShelfArrange bookShelf=new BookShelfArrange(5);
bookShelf.appendBook(new Book("A"));
bookShelf.appendBook(new Book("B"));
bookShelf.appendBook(new Book("C"));
bookShelf.appendBook(new Book("D"));
bookShelf.appendBook(new Book("E"));
Iterator it=bookShelf.iterator();
while(it.hasNext()){
System.out.println(((Book)it.next()).getName());
}
System.out.println("End");
}
}
*주석 부분만 바꾸면 집합체를 변경할 수 있다.
댓글 없음:
댓글 쓰기