①图解设计模式之 【Iterator】模式

首先附上 示例程序类图:

①图解设计模式之 【Iterator】模式

 

实例源代码:

Aggregate.java

package IteratorPattern;

import java.util.Iterator;

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

 Book.java

package IteratorPattern;

public class Book {
	private String name;

	public Book(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
}

 

 BookShelf.java

package IteratorPattern;

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) {
		this.books[last] = book;
		last++;
	}

	public int getLength() {
		return last;
	}

	@Override
	public Iterator iterator() {

		return new BookShelfIterator(this);
	}

}

 

BookShelfIterator.java 

 

package IteratorPattern;

import java.util.Iterator;

public class BookShelfIterator implements Iterator {
	private BookShelf bookShelf;
	private int index;

	public BookShelfIterator(BookShelf bookShelf) {
		this.bookShelf = bookShelf;
		this.index = 0;
	}

	@Override
	public boolean hasNext() {
		if (index < bookShelf.getLength()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object next() {
		Book book = bookShelf.getBookAt(index);
		index++;
		return book;
	}

}

Main.java 

 

package IteratorPattern;

import java.util.Iterator;

public class Main {

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

}

①图解设计模式之 【Iterator】模式

 

①图解设计模式之 【Iterator】模式

总结: 

1).为什么要引入Iterator 这种设计模式呢?

 因为Iterator 将遍历与实现分离开来.

例如:while (it.hasNext()) {
            Book book = (Book) it.next();
            System.out.println(book.getName());
        }

这段代码中,只是使用了Iterator 的 hasNext() 和next() 方法,并没有调用BookShelf 方法.

也就是,这里while循环并不依赖于 BookShelf 的实现

设计模式的作用就是帮助我们编写可复用的类。“可复用”就是将类实现为“组件”,当一个组件发生改变时,不需要对其他的组件进行修改或只需很小的修改即可应对。

就好比汽车的轮带并不单独针对某一款汽车而设计,而是针对所有汽车而设计,即使你把汽车改装成飞机,只要轮胎没问题,照样能跑.

源代码下载地址:https://download.csdn.net/download/csp_6666/11064624