@ 기본 패턴
- Iterator(반복자) : interface Iterator
package Iterator;
public interface Iterator {
public abstract Object next();
public abstract boolean hasNext();
}
- Aggregate(집합체) : interface Aggregate
package Iterator;
public interface Aggregate {
public abstract Iterator iterator();
public abstract int getLength();
public abstract Object getBookAt(int index);
}
@ 구현
- Element(요소) : Book
package Iterator;
public class Book {
String name;
public Book(String name) {
this.name = name;
}
String getName(){
return name;
}
}
- ConcreteAggregate(구체적인 집합체) : BookShelf
package Iterator;
import java.util.ArrayList;
public class BookShelf implements Aggregate {
private ArrayList<Book> books;
public BookShelf() {
this.books=new ArrayList<Book>();
}
public void appendBook(Book book){
this.books.add(book);
}
public Book getBookAt(int index){
return this.books.get(index);
}
public int getLength(){
return this.books.size();
}
public boolean findBook(String name){
int flag=0;
for(int i=0;i<this.getLength();i++){
if(this.getBookAt(i).getName().equalsIgnoreCase(name)){
flag=1;
}
}
if(flag==1){
return true;
}else{
return false;
}
}
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
- ConcreteIterator(구체적인 반복자) : BookShelfIterator
package Iterator;
public class BookShelfIterator implements Iterator {
private Aggregate bookShelf;
private int index;
public BookShelfIterator(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 Iterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BookShelf bookShelf=new BookShelf();
String name="";
int value=0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("책입력 1번");
System.out.println("전체 책 출력 2번");
System.out.println("책검색 3번");
System.out.println("끝내기 4번");
System.out.print(">> ");
value = Integer.valueOf(br.readLine());
if(value==1){
System.out.print("책의 제목을 입력하시오 : ");
name = br.readLine();
bookShelf.appendBook(new Book(name));
System.out.println();
}else if(value==2){
Iterator it=bookShelf.iterator();
while(it.hasNext()){
System.out.println(((Book)it.next()).getName());
}
System.out.println("총 "+bookShelf.getLength()+"권이 서가에 존재합니다.");
System.out.println();
}else if(value==3){
System.out.print("검색을 원하는 책의 제목을 입력하시오 : ");
name = br.readLine();
if(bookShelf.findBook(name)==true){
System.out.println("검색하신 책이 서가에 존재합니다.");
}else{
System.out.println("검색하신 책이 서가에 존재하지 않습니다.");
}
System.out.println();
}else if(value==4){
System.out.println("서가 프로그램을 종료합니다.");
break;
}else{
System.out.println("잘못된 숫자를 입력하셨습니다.");
System.out.println();
}
}
}
}
댓글 없음:
댓글 쓰기