2004-10-08

FRIDAY Party 作業1

練習畫UML圖

這個程式是把書籍(Book)放到書架(BookShelf)上,並依序輸出書名。

List 1-1 Aggregate 介面
public interface Aggregate {
  public abstract Iterator iterator();
}
List 1-2 Iterator 介面
public interface Iterator {
  public abstract boolean hasNext();
  public abstract Object next();
}
List 1-3 Book 類別
public class Book {
  private String name ="";
  public Book(String name){
     this.name = name;
  }
  public String getName(){
     return name;
  }
}
List 1-4 BookShelf類別
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 appeandBook(Book book){
     this.books[last] = book;
     last++;
  }
  public int getLength(){
     return last;
  }
  public Iterator iterator(){
     return new BookShelfIterator(this);
  }
}
List 1-5 BookShelfIterator類別
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;
   }
}
List 1-6 Main類別
public class Mian {

  public static void main(String[] args) {
     BookShelf bookShelf = new BookShelf(4);
     bookShelf.appeandBook(new Book("Around the World"));
     bookShelf.appeandBook(new Book("Bible"));
     bookShelf.appeandBook(new Book("Cinderrella"));
     bookShelf.appeandBook(new Book("Daddy-Long-Legs"));
     Iterator it = bookShelf.iterator();
     while(it.hasNext()){
        Book book = (Book)it.next();
        System.out.println("" + book.getName());
     }
  }
}

--
加油囉~

1 則留言:

SwanBear 提到...

這個是Iterator Design Pattern
做完記得把UMI圖貼上來喔~ :)