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()); } } }
原文地址:https://www.cnblogs.com/yangchaojie/p/8146724.html
时间: 2024-11-08 23:55:53