1. 程式人生 > >java 開發模式之十 : 迭代器模式

java 開發模式之十 : 迭代器模式

原理或定義

迭代器模式叫做遊標(Cursor)模式。GOF給出的定義:提供一種方法訪問一個容器(container)物件中的各個元素,而又不暴露該物件的內部細節

結構

迭代器角色(Iterator: 負責定義訪問和遍歷元素的介面。
具體迭代器角色(Concrete Iterator:實現迭代器介面,並要記錄遍歷中的當前位置。
容器角色(Aggregate) 負責提供建立具體迭代器角色的介面。
具體容器角色(ConcreteAggregate:實現建立具體迭代器角色的介面, 這個具體迭代器角色與該容器的結構相

類圖

案例與程式碼

本模式使用兩個菜館合併後的選單問題來作為案例

蛋糕店與餐廳合併後,怎麼統一管理選單專案
問題:一個用ArrayList管理選單,一個用陣列管理

一般設計方案:

通用選單類:

public class MenuItem {
	private String name,description;
	private boolean vegetable;
	private float price;
	public MenuItem(String name,String description,boolean vegetable,float price)
	{
		this.name=name;
		this.description=description;
		this.vegetable=vegetable;
		this.price=price;
		
	}
	public String getName()
	{
		return name;
	}
	public String getDescription()
	{
		return description;
	}
	public float getPrice()
	{
		return price;
	}
	public boolean  isVegetable()
	{
		return vegetable;
	}
}

餐廳類:

public class CakeHouseMenu {
	private ArrayList<MenuItem> menuItems;

	public CakeHouseMenu() {
		menuItems = new ArrayList<MenuItem>();
		
		addItem("KFC Cake Breakfast","boiled eggs&toast&cabbage",true,3.99f);
		addItem("MDL Cake Breakfast","fried eggs&toast",false,3.59f);
		addItem("Stawberry Cake","fresh stawberry",true,3.29f);
		addItem("Regular Cake Breakfast","toast&sausage",true,2.59f);
	}

	private void addItem(String name, String description, boolean vegetable,
			float price) {
		MenuItem menuItem = new MenuItem(name, description, vegetable, price);
		menuItems.add(menuItem);
	}
	public ArrayList<MenuItem> getMenuItems() {
		return menuItems;
	}
	
	//其他功能程式碼
}
public class DinerMenu {
private final static int Max_Items=5;
public int numberOfItems=0;
private MenuItem[] menuItems;

public DinerMenu()
{
menuItems=new MenuItem[Max_Items] ;
addItem("vegetable Blt","bacon&lettuce&tomato&cabbage",true,3.58f);
addItem("Blt","bacon&lettuce&tomato",false,3.00f);
addItem("bean soup","bean&potato salad",true,3.28f);
addItem("hotdog","onions&cheese&bread",false,3.05f);


}
private void addItem(String name, String description, boolean vegetable,
float price) {
MenuItem menuItem = new MenuItem(name, description, vegetable, price);
if(numberOfItems>=Max_Items)
{
System.err.println("sorry,menu is full!can not add another item");
}else{
menuItems[numberOfItems]=menuItem;
numberOfItems++;
}

}

public MenuItem[] getMenuItems() {
return menuItems;
}
}
管理類 / 服務員類:
public class Waitress {
	private CakeHouseMenu mCakeHouseMenu;
	private DinerMenu mDinerMenu;
	private ArrayList<MenuItem> cakeitems;
	private MenuItem[] dineritems;

	
	
	public Waitress() {
		mCakeHouseMenu = new CakeHouseMenu();
		cakeitems = mCakeHouseMenu.getMenuItems();

		mDinerMenu = new DinerMenu();
		dineritems = mDinerMenu.getMenuItems();
	}

	public void printMenu() {
		MenuItem menuItem;
		for (int i = 0, len = cakeitems.size(); i < len; i++) {
			menuItem = cakeitems.get(i);
			System.out.println(menuItem.getName() + "***"
					+menuItem.getPrice()+"***"+ menuItem.getDescription());

		}
		for (int i = 0, len = mDinerMenu.numberOfItems; i < len; i++) {
			menuItem = dineritems[i];
			System.out.println(menuItem.getName() + "***"
					+menuItem.getPrice()+"***"+ menuItem.getDescription());

		}

	}

	public void printBreakfastMenu() {

	}

	public void printLunchMenu() {

	}

	public void printVegetableMenu() {

	}
}

顧客 / 測試類:
public class MainTest {
	public static void main(String[] args) {
	
		Waitress mWaitress=new Waitress();
		//服務員展示2家餐廳合併的選單
		mWaitress.printMenu();
	}
}

此設計違法單一責任原則,當新增新餐廳,列印選單的方法需要改變,而且複雜度和新餐廳的資料結構的複雜度成正比。

迭代器模式的設計方案:

通用選單類不變。

迭代器角色(Iterator

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

}

餐廳類:
public class CakeHouseMenu {
	private ArrayList<MenuItem> menuItems;
	
	
	public CakeHouseMenu() {
		menuItems = new ArrayList<MenuItem>();
		
		addItem("KFC Cake Breakfast","boiled eggs&toast&cabbage",true,3.99f);
		addItem("MDL Cake Breakfast","fried eggs&toast",false,3.59f);
		addItem("Stawberry Cake","fresh stawberry",true,3.29f);
		addItem("Regular Cake Breakfast","toast&sausage",true,2.59f);
	}

	private void addItem(String name, String description, boolean vegetable,
			float price) {
		MenuItem menuItem = new MenuItem(name, description, vegetable, price);
		menuItems.add(menuItem);
	}
	

	
	public Iterator getIterator()
	{
		return new CakeHouseIterator() ;
	}
	
	class CakeHouseIterator implements  Iterator
	 {		
		private int position=0;
		public CakeHouseIterator()
		{
			  position=0;
		}
		
		 	@Override
			public boolean hasNext() {
			// TODO Auto-generated method stub
			if(position<menuItems.size())
			{
				return true;
			}
			
			return false;
		}

		@Override
		public Object next() {
			// TODO Auto-generated method stub
			MenuItem menuItem =menuItems.get(position);
			position++;
			return menuItem;
		}};
	//其他功能程式碼
	
}

public class DinerMenu {
private final static int Max_Items = 5;
private int numberOfItems = 0;
private MenuItem[] menuItems;


public DinerMenu() {
menuItems = new MenuItem[Max_Items];
addItem("vegetable Blt", "bacon&lettuce&tomato&cabbage", true, 3.58f);
addItem("Blt", "bacon&lettuce&tomato", false, 3.00f);
addItem("bean soup", "bean&potato salad", true, 3.28f);
addItem("hotdog", "onions&cheese&bread", false, 3.05f);


}


private void addItem(String name, String description, boolean vegetable,
float price) {
MenuItem menuItem = new MenuItem(name, description, vegetable, price);
if (numberOfItems >= Max_Items) {
System.err.println("sorry,menu is full!can not add another item");
} else {
menuItems[numberOfItems] = menuItem;
numberOfItems++;
}


}


public Iterator getIterator() {
return new DinerIterator();
}


class DinerIterator implements Iterator {
private int position;


public DinerIterator() {
position = 0;
}


@Override
public boolean hasNext() {
// TODO Auto-generated method stub
if (position < numberOfItems) {
return true;
}

return false;
}


@Override
public Object next() {
// TODO Auto-generated method stub
MenuItem menuItem = menuItems[position];
position++;
return menuItem;
}
};
}

服務員類:
public class Waitress {
	private ArrayList<Iterator> iterators=new ArrayList<Iterator>();


	public Waitress() {
		
	}
	public void addIterator(Iterator iterator)
	{
		iterators.add(iterator);
		
	}
	public void printMenu() {
		Iterator iterator;
		MenuItem menuItem;
		for (int i = 0, len = iterators.size(); i < len; i++) {
			iterator = iterators.get(i);
			
			while(iterator.hasNext())
			{
				menuItem=(MenuItem)	iterator.next();
				System.out.println(menuItem.getName() + "***"
						+menuItem.getPrice()+"***"+ menuItem.getDescription());

			}
			
			
		}
		
		

	}
}

測試類:
public class MainTest {
	public static void main(String[] args) {
		Waitress mWaitress=new Waitress();
		CakeHouseMenu mCakeHouseMenu = new CakeHouseMenu();
		DinerMenu	mDinerMenu = new DinerMenu();
		
		mWaitress.addIterator(mCakeHouseMenu.getIterator());
		mWaitress.addIterator(mDinerMenu.getIterator());
		mWaitress.printMenu();
	}
}

該案例可以直接使用JDK內建的迭代器介面作為迭代器角色:Iterator

迭代器模式:提供一種方法順序訪問一個聚合物件中的各個物件。



單一責任原則:一個類應該只有一個引起變化的原因.

使用場景

1. 訪問一個聚合物件的內容而無需暴露它的內部表示

2.支援對聚合物件的多種遍歷

3.為遍歷不同的聚合結構提供一個統一的介面

優缺點

主要優點有:

1. 簡化了遍歷方式。

2.可以提供多種遍歷方式,比如說對有序列表,我們可以根據需要提供正序遍歷,倒序遍歷兩種迭代器。

3.封裝性良好,使用者只需要得到迭代器就可以遍歷,而對於遍歷演算法則不用去關心

缺點主要有

對於比較簡單的遍歷(像陣列或者有序列表),使用迭代器方式遍歷較為繁瑣,大家可能都有感覺,像ArrayList,我們寧可願意使用for迴圈和get方法來遍歷集合

迭代器模式是與集合共生共死的,一般來說,我們只要實現一個集合,就需要同時提供這個集合的迭代器,就像java中的CollectionListSetMap等,這些集合都有自己的迭代器。假如我們要實現一個這樣的新的容器,當然也需要引入迭代器模式,給我們的容器實現一個迭代器