设计模式(1) — 迭代模式

    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

相关文章