现在的位置: 首页 > 综合 > 正文

Iterator——设计模式

2013年02月06日 ⁄ 综合 ⁄ 共 1908字 ⁄ 字号 评论关闭

1.用到了java的API Iterator 类的示例:

import java.util.*;
class MapTest {
	public static void main(String[] args) {
		Map<String,Integer> map = new HashMap<String,Integer>();
		map.put("a",1);
		map.put("b",2);
		map.put("c",3);
		map.put("d",4);
		map.put("e",5);
		
		Set<String> set = map.keySet();
		System.out.println(set);
		for(Iterator<String> iter = set.iterator();iter.hasNext();) {
			String s = (String)iter.next();
			System.out.println(s + ":" + map.get(s));
		}
		
	}	
}

一点思考:

Iterator类是通过集合类的iterator()方法得到的。

有hasNext()与next()方法;

2.JAVA迭代器模式详解:

1)成员:

接口:Aggregate、Iterator

类:Book、BookShelf、BookShelfIterator

2)示例:

interface Aggregate {
	public abstract Iterator iterator();	
	
}

interface Iterator {
	public abstract boolean hasNext();
	public abstract Object next();
}


class Book {
	private String name = "";
	public Book(String name) {
		this.name = name;	
	}	
	public String getName() {
		return name;	
	}
}



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;	
	}
	public Iterator iterator() {
		return new BookShelfIterator(this);	
	}
	
}




class BookShelfIterator implements Iterator {
	private BookShelf bookShelf;
	private int index;
	public BookShelfIterator(BookShelf bookShelf) {
		this.bookShelf = bookShelf;
		this.index = 0;	
	}	
	public boolean hasNext() {
		if (index < bookShelf.getLength()) {
			return true;	
		} 	
		else {
			return false;	
		}
	}
	
	public Object next() {
		Book book = bookShelf.getBookAt(index);
		index++;
		return book;	
	}
}

public class Main {
	public static void main(String[] args) {
		BookShelf bookShelf = new BookShelf(4);
		bookShelf.appendBook(new Book("C++"));
		bookShelf.appendBook(new Book("JAVA"));	
		bookShelf.appendBook(new Book("PATTERN"));
		bookShelf.appendBook(new Book("Operation System"));
		Iterator it = bookShelf.iterator();
		while(it.hasNext()) {
			Book book = (Book)it.next();
			System.out.println("" + book.getName());
		}
	}	
}

Aggregate接口定义了得到Iterator类的方法;

Book是对象;

BookShelf保存Book对象,相当于集合类;

BookShelfIterator是实现了Iterator的类,构造方法传入了BookShelf对象。

抱歉!评论已关闭.