迭代器模式

概述

 

 

迭代器的结构

 

public class Book {
	private String ISBN;
	private String name;
	private double price;
	
	public Book(String isbn, String name, double price) {
		ISBN = isbn;
		this.name = name;
		this.price = price;
	}

	public String getISBN() {
		return ISBN;
	}

	public void setISBN(String isbn) {
		ISBN = isbn;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}
	
	public void display() {
		System.out.println("ISBN=" + ISBN + ",name=" + name + ",price" + price);
	}
	
	
}
public class BookList {
	private List<Book> bookList;
	private int index;
	private Iterator iterator;
	
	public BookList() {
		bookList = new ArrayList<Book>();
	}
	
	//添加书籍
	public void addBook(Book book) {
		bookList.add(book);
	}
	
	//删除书籍
	public void deleteBook(Book book) {
		int bookIndex = bookList.indexOf(book);
		bookList.remove(bookIndex);
	}
	
//	//判断是否有下一本书
//	public boolean hasNext() {
//		if(index >= bookList.size()) {
//			return false;
//		}
//		return true;
//	}
//	
//	//获得下一本书
//	public Book getNext() {
//		return bookList.get(index++);
//	}
	
//	public List<Book> getBookList() {
//		return bookList;
//	}
	
	public Iterator Iterator() {
		return new Itr();
	}
	
	private class Itr implements Iterator{

		public boolean hasNext() {
			if(index >= bookList.size()) {
				return false;
			}
			return true;
		}

		public Object next() {
			return bookList.get(index++);
		}

		public void remove() {
			
		}
		
	}
	
}
public class MainClss {
	public static void main(String[] args) {
		BookList bookList = new BookList();
		
		Book book1 = new Book("010203","Java编程思想",90);
		Book book2 = new Book("010204","Java从入门到精通",60);
		
		bookList.addBook(book1);
		bookList.addBook(book2);
		
//		while(bookList.hasNext()) {
//			Book book = bookList.getNext();
//			book.display();
//		}
		
//		List<Book> bookDateList = bookList.getBookList();
//		for(int i = 0; i < bookDateList.size(); i++) {
//			Book book = bookDateList.get(i);
//			book.display();
//		}
		
		Iterator iter = bookList.Iterator();
		while(iter.hasNext()) {
			Book book = (Book) iter.next();
			book.display();
		}
		
		
	}
}

迭代器模式优缺点

迭代器模式应用