1. 程式人生 > >設計模式(1) -- 叠代模式

設計模式(1) -- 叠代模式

初始 als aggregate font blog fit public get linu

    Iterator(叠代器)接口在Java中可以用來嵌入對象當中來實現具體應用,在設計模式中強調的是"低耦合","高復用","不要用具體代碼來編程,要優先使用接口和抽象類來編程。"

    這個實例當中不管BookShelf如何變化,只要BookShelf類可以返回重寫了Iterator方法(hasNext,Next)的BookShelfIterator類,無論改成數組還是集合測設代碼都可以正常運轉,這便是組件化,當一個組件發生改變時,可以不用修改其他組件或者很小改動。

    實例:

      集合接口:

package com.book;

import java.util.Iterator;

public interface Aggregate {
        public abstract Iterator iterator();
}

       書類:

    package com.book;

public class Book {
        private    String BookName;

        public String getBookName() {
            return BookName;
        }

        public void setBookName(String bookName) {
            BookName = bookName;
        }
        
        
}

  

    書架類:

package com.book;

import java.util.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) {
        Books[last] = book;
        last++;
    }
    //獲取長度
    public int getLength() {
        return last;
    }
    
    
    @Override
    public Iterator iterator() {
        // TODO Auto-generated method stub
        return new BookSelfIterator(this);
    }
    
        
}

    書架叠代:

package com.book;

import java.util.Iterator;

public class BookSelfIterator implements Iterator{
    //定義一個書架
    private BookShelf bookSelf;
    //定義下標
    private int index;
    
    //初始化
    public BookSelfIterator(BookShelf bookShelf) {
        this.bookSelf = bookShelf;
        index = 0;
    }
    
    
    @Override
    public boolean hasNext() {
        // TODO Auto-generated method stub
        if(index<bookSelf.getLength()) {
            return true;
        }else {
        return false;
        }
    }

    @Override
    public Object next() {
        // TODO Auto-generated method stub
        Book book = bookSelf.getBookAt(index);
        index++;
        return book;
    }

}

   測試:

package com.book;

public class TextMain {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf(6);
        Book book_1 = new Book();
        Book book_2 = new Book();
        Book book_3 = new Book();
        book_1.setBookName("圖解設計模式");
        book_2.setBookName("鳥歌的Linux私房菜");
        book_3.setBookName("算法導論");
        bookShelf.appendBook(book_1);
        bookShelf.appendBook(book_2);
        bookShelf.appendBook(book_3);;
        BookSelfIterator bookShelfIterator  = new BookSelfIterator(bookShelf);
        while(bookShelfIterator.hasNext()) {
            Book book = (Book) bookShelfIterator.next();
            System.out.println(book.getBookName());
        }
    }
}

技術分享圖片

設計模式(1) -- 叠代模式