迭代器模式――Head First Design Patterns

2014-11-24 07:47:13 · 作者: · 浏览: 0

定义:迭代器模式提供一种不暴露集合就能访问集合内多态对象的途径

使用场景:需要遍历某个集合时

类图:

\

代码样例:

package headfirst.iterator.dinermerger;

public class MenuItem {
	String name;
	String description;
	boolean vegetarian;
	double price;
 
	public MenuItem(String name, 
	                String description, 
	                boolean vegetarian, 
	                double price) 
	{
		this.name = name;
		this.description = description;
		this.vegetarian = vegetarian;
		this.price = price;
	}
  
	public String getName() {
		return name;
	}
  
	public String getDescription() {
		return description;
	}
  
	public double getPrice() {
		return price;
	}
  
	public boolean isVegetarian() {
		return vegetarian;
	}
	public String toString() {
		return (name + ", $" + price + "\n   " + description);
	}
}


package headfirst.iterator.dinermerger;

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


package headfirst.iterator.dinermerger;

public class ArrayIterator implements Iterator {
	MenuItem[] items;
	int position = 0;
 
	public ArrayIterator(MenuItem[] items) {
		this.items = items;
	}
 
	public Object next() {
		MenuItem menuItem = items[position];
		position = position + 1;
		return menuItem;
	}
 
	public boolean hasNext() {
		if (position >= items.length || items[position] == null) {
			return false;
		} else {
			return true;
		}
	}
}


优点:1)提供一种访问集合元素的统一方法,使用者不需要关注该集合的底层实现 2)将遍历集合和管理集合分离,使集合本身仅关注于管理

缺点:

类似的设计模式:

配套的内功心法:1)一个类应该只有一个改变的理由 2)凝聚性用来度量一个类或者模块仅关注一个功能的程度,一个类如果仅包含一组非常相近的功能,我们称这个类具有高凝聚性。