《HeadFirst设计模式》第九章-1迭代器模式

本文通过《HeadFirst设计模式》第九章-1迭代器模式介绍,阐述了在对象村煎饼店和餐厅合并后,如何利用迭代器模式解决菜单遍历的问题。通过迭代器接口和实现,实现了菜单类的遍历功能,遵循单一责任原则,提高代码的内聚性和可扩展性。同时,文章探讨了Java5中迭代器和集合的改进,引入了foreach语句简化遍历操作。
摘要由CSDN通过智能技术生成

1.声明

设计模式中的设计思想、图片和部分代码参考自《Head First设计模式》作者Eric Freeman & Elisabeth Freeman & Kathy Siezza & Bert Bates。

在这里我只是对这本书进行学习阅读,并向大家分享一些心得体会。

2.需求

对象村有一家煎饼店和一家餐厅,煎饼店主营早餐,餐馆主营午餐,为了实现双赢·,两家店决定合并为一家,这样顾客就既能吃到早餐,又能吃到午餐了。

两家餐厅共同协商了,餐厅的菜单软件系统,它们共同敲定了单个餐品的类设计-MenuItem。

单个菜品-MenuItem

//单个菜品结构
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);
	}
}

有了单个菜品的结构,接下来自然而然就是制定菜单类了,但是两家餐厅进行到这步,就进行不下去了,原因就是两家原来都有自己的菜单类设计,并且已经使用很久,不方便更改,煎饼店使用的是ArrayList来存储MenuItem,餐厅使用的是数组来存储MenuItem。

煎饼店菜单类:

//煎饼店菜单类
public class PancakeHouseMenu {
	
	//使用ArrayList装载菜品
	ArrayList<MenuItem> menuItems;
 
	public PancakeHouseMenu() {
		menuItems = new ArrayList<MenuItem>();
    
		//调用addItem添加菜品
		addItem("K&B's Pancake Breakfast", 
			"Pancakes with scrambled eggs, and toast", 
			true,
			2.99);
 
		addItem("Regular Pancake Breakfast", 
			"Pancakes with fried eggs, sausage", 
			false,
			2.99);
 
		addItem("Blueberry Pancakes",
			"Pancakes made with fresh blueberries",
			true,
			3.49);
 
		addItem("Waffles",
			"Waffles, with your choice of blueberries or strawberries",
			true,
			3.59);
	}

	public void addItem(String name, String description,
	                    boolean vegetarian, double price)
	{
		MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
		//放入集合
		menuItems.add(menuItem);
	}
 
	//返回全部菜品
	public ArrayList<MenuItem> getMenuItems() {
		return menuItems;
	}
  
	// other menu methods here
}

餐厅菜单类:

//餐厅菜单类
public class DinerMenu {
	
	//数组容量
	static final int MAX_ITEMS = 6;
	//当前菜品数量
	int numberOfItems = 0;
	//使用数组存储MenuItem
	MenuItem[] menuItems;
  
	public DinerMenu() {
		menuItems = new MenuItem[MAX_ITEMS];
 
		addItem("Vegetarian BLT",
			"(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99);
		addItem("BLT",
			"Bacon with lettuce & tomato on whole wheat", false, 2.99);
		addItem("Soup of the day",
			"Soup of the day, with a side of potato salad", false, 3.29);
		addItem("Hotdog",
			"A hot dog, with saurkraut, relish, onions, topped with cheese",
			false, 3.05);
		addItem("Steamed Veggies and Brown Rice",
			"Steamed vegetables over brown rice", true, 3.99);
		addItem("Pasta",
			"Spaghetti with Marinara Sauce, and a slice of sourdough bread",
			true, 3.89);
	}
  
	public void addItem(String name, String description, 
	                     boolean vegetarian, double price) 
	{
		MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
		if (numberOfItems >= MAX_ITEMS) {
			System.err.println("Sorry, menu is full!  Can't add item to menu");
		} else {
			menuItems[numberOfItems] = menuItem;
			numberOfItems = numberOfItems + 1;
		}
	}
 
	//返回全部菜品
	public MenuItem[] getMenuItems() {
		return menuItems;
	}
	
	// other menu methods here
}

那么这样的问题在哪呢?设想,如果我们想打印菜单,那我们需要先通过getMenuItems()获得菜品集合:

现在我们遍历得到的菜品集合,并逐一打印:

由上可知,只要涉及到打印的地方,我们对煎饼店和餐厅的处理都需要分别对待。打印这两个餐厅,就需要两种循环,那么设想如果再加入一个晚餐的餐厅,那是不是还要准备一套循环。这简直太麻烦了。

既然两个餐厅都不想修改代码,那么我们想想,可不可以为这两个餐厅设计一个公共接口,再把遍历封装到菜单类的内部,然后调用接口方法进行遍历呢?

下面再分析一下二者的不同:

解决方案的构思:

3.迭代器模式

迭代器接口:

一旦实现了这个接口,就可以为各种对象集合实现迭代器:数组、列表、散列表等。

下面我们创建一个迭代器接口。

餐厅菜单迭代器(实现java.util.Iterator):

//餐厅菜单迭代器
public class DinerMenuIterator implements Iterator {
	
	//菜品数组
	MenuItem[] items;
	//记录当前数组遍历的位置
	int position = 0;
 
	public DinerMenuIterator(MenuItem[] items) {
		this.items = items;
	}
 
	//取得下一个元素
	public MenuItem next() {
		MenuItem menuItem = items[position];
		position = position + 1;
		return menuItem;
	}
 
	//是否还有下一个元素
	public boolean hasNext() {
		
		//如果到达数组末尾,或者下一项是null,那么都认为无下一个元素
		if (position >= items.length || items[position] == null) {
			return false;
		} else {
			return true;
		}
	}
}

菜单超类:

public interface Menu {
	public Iterator<MenuItem> createIterator();
}

煎饼店菜单类:

public class PancakeHouseMenu implements Menu {
	ArrayList<MenuItem> menuItems;
 
	public PancakeHouseMenu() {
		menuItems = new ArrayList<MenuItem>();
    
		addItem("K&B's Pancake Breakfast", 
			"Pancakes with scrambled eggs, and toast", 
			true,
			2.99);
 
		addItem("Regular Pancake Breakfast", 
			"Pancakes with fried eggs, sausage", 
			false,
			2.99);
 
		addItem("Blueberry Pancakes",
			"Pancakes made with fresh blueberries, and blueberry syrup",
			true,
			3.49);
 
		addItem("Waffles",
			"Waffles, with your choice of blueberries or strawberries",
			true,
			3.59);
	}

	public void addItem(String name, String description,
	                    boolean vegetarian, double price)
	{
		MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
		menuItems.add(menuItem);
	}
 
	public ArrayList<MenuItem> getMenuItems() {
		return menuItems;
	}
  
	public Iterator<MenuItem> createIterator() {
		return menuItems.iterator();
	}
  
	// other menu methods here
}

餐厅店菜单类:

public class DinerMenu implements Menu {
	static final int MAX_ITEMS = 6;
	int numberOfItems = 0;
	MenuItem[] menuItems;
  
	public DinerMenu() {
		menuItems = new MenuItem[MAX_ITEMS];
 
		addItem("Vegetarian BLT",
			"(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99);
		addItem("BLT",
			"Bacon with lettuce & tomato on whole wheat", false, 2.99);
		addItem("Soup of the day",
			"Soup of the day, with a side of potato salad", false, 3.29);
		addItem("Hotdog",
			"A hot dog, with saurkraut, relish, onions, topped with cheese",
			false, 3.05);
		addItem("Steamed Veggies and Brown Rice",
			"Steamed vegetables over brown rice", true, 3.99);
		addItem("Pasta",
			"Spaghetti with Marinara Sauce, and a slice of sourdough bread",
			true, 3.89);
	}
  
	public void addItem(String name, String description, 
	                     boolean vegetarian, double price) 
	{
		MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
		if (numberOfItems >= MAX_ITEMS) {
			System.err.println("Sorry, menu is full!  Can't add item to menu");
		} else {
			menuItems[numberOfItems] = menuItem;
			numberOfItems = numberOfItems + 1;
		}
	}
  
	public Iterator<MenuItem> createIterator() {
		return new DinerMenuIterator(menuItems);
	}

}

女招待员类(含有打印菜单等方法):

public class Waitress {
	Menu pancakeHouseMenu;
	Menu dinerMenu;
 
	//可以处理两种餐厅的菜单
	public Waitress(Menu pancakeHouseMenu, Menu dinerMenu) {
		this.pancakeHouseMenu = pancakeHouseMenu;
		this.dinerMenu = dinerMenu;
	}
 
	public void printMenu() {
		Iterator<MenuItem> pancakeIterator = pancakeHouseMenu.createIterator();
		Iterator<MenuItem> dinerIterator = dinerMenu.createIterator();

		System.out.println("MENU\n----\nBREAKFAST");
		printMenu(pancakeIterator);
		System.out.println("\nLUNCH");
		printMenu(dinerIterator);
	}
 
	private void printMenu(Iterator<MenuItem> iterator) {
		while (iterator.hasNext()) {
			MenuItem menuItem = iterator.next();
			System.out.print(menuItem.getName() + ", ");
			System.out.print(menuItem.getPrice() + " -- ");
			System.out.println(menuItem.getDescription());
		}
	}

}

测试方法:

public class MenuTestDrive {
	
	public static void main(String args[]) {
		//煎饼店菜单
		PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
		//餐厅菜单
		DinerMenu dinerMenu = new DinerMenu();
		//女招待员
		Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu);
		//打印菜单
		waitress.printMenu();
	}
}

输出结果:

MENU
----
BREAKFAST
K&B's Pancake Breakfast, 2.99 -- Pancakes with scrambled eggs, and toast
Regular Pancake Breakfast, 2.99 -- Pancakes with fried eggs, sausage
Blueberry Pancakes, 3.49 -- Pancakes made with fresh blueberries, and blueberry syrup
Waffles, 3.59 -- Waffles, with your choice of blueberries or strawberries

LUNCH
Vegetarian BLT, 2.99 -- (Fakin') Bacon with lettuce & tomato on whole wheat
BLT, 2.99 -- Bacon with lettuce & tomato on whole wheat
Soup of the day, 3.29 -- Soup of the day, with a side of potato salad
Hotdog, 3.05 -- A hot dog, with saurkraut, relish, onions, topped with cheese
Steamed Veggies and Brown Rice, 3.99 -- Steamed vegetables over brown rice
Pasta, 3.89 -- Spaghetti with Marinara Sauce, and a slice of sourdough bread

类图:

4.定义迭代器模式

4.1定义

迭代器模式

提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。

迭代器模式让我们能游走聚合内的每一个元素,而不暴露其内部的表示。

把游走的任务放在迭代器上,而不是聚合上。这样简化了聚合的接口和实现,也让责任各得其所。

4.2类图

4.3问答

迭代器有"内部的"迭代器和"外部的"迭代器,我们实现的是那种迭代器?答:我们实现的是外部迭代器。也就是说客户可以通过next()取得下一个元素。而内部的迭代器则是由迭代器自己控制,在这种情况下,因为是由迭代器自行在元素之间游走,所以我们必须告诉迭代器在游走的过程中,要做些什么事情,也就是说我们必须将操作传入迭代器。因为客户无法控制遍历的过程,所以内部迭代器比外部迭代器更没有弹性。

迭代器可以被实现成向后移动吗?答:绝对可以。在这种情况下,需要新添两个方法,一个是判断是否达到了集合的最前面,另一个方法是获取前一个元素。Java的Collection Framework提供另一种迭代器接口,成为ListIterator。这个迭代器在标准的迭代器接口上多加了一个previous()和一些其他的方法。任何实现了List接口的集合,都支持这样的做法。

对于散列表这样的集合,元素之间并没有明显的次序关系,应该如何遍历?答:迭代器意味着没有次序。只是去除所有元素,并不代表去除元素的先后就代表元素的大小次序。对于迭代器来说,数据结构可以是有次序的,或是没有次序的,甚至数据可以是重复的。除非某个集合的文件有特别说明,否则不可以对迭代器所取出的元素大小顺序做出假设。

5.单一责任设计原则

我们知道煎饼店菜单类(PancakeHouseMenu)和餐厅店菜单类(DinerMenu)都有着对自己的集合进行管理的功能:addItem,那么我们为什么不把迭代功能也放在这两个类中,而还要麻烦的去新设计两个类:PancakeHouseMenuIterator和DinerMenuIterator呢?

这就设计到了一个新的设计原则-单一责任原则,先看定义。

设计原则

一个类应该只有一个引起变化的原因。

当我们运行一个类不但要完成自己的事情(管理某种集合),而且还要同时负担更多的责任(例如遍历)时,我们就给了这个类两个变化的因素。如果我们这个集合改变的话,那么这个类需要改变;如果我们的遍历方式改变的话,这个类还是需要改变。

我们知道要避免类内的改变,因为修改代码很容易造成许多潜在的错误。如果有一个类具有两个改变的因素,这会使得将来该类的变化几率上升,而当它真的改变时,我们的设计中同时有两个方面将会受到影响。

单一责任原则,告诉我们给一个类只指派一个责任。但是这只是听起来比较容易,但是做起来并不简单。因为区分设计中的责任,是最困难的事情之一。我们的大脑很习惯看着一大群行为,然后将它们聚在一起,尽管他们可能属于两个或多个不同的责任。想要成功的唯一方法,就是努力地检查我们地设计,随着系统地成长,随时观察有没有迹象显示某个类改变的原因超出一个。

内聚(cohesion)

用来度量一个类或者模块紧密地达到单一目的或责任。

当一个模块或一个类被设计成只支持一组相关的功能时,我们说它具有高内聚;反之,当被设计成支持一组不相关的功能时,我们说它具有低内聚。

内聚是一个比单一原则更普遍的概念,但两者其实关系还是很密切的。遵守这个原则的类容易具有很高的凝聚力,而且比背负许多责任的低内聚类更容易维护。

6.新的需求

对象村餐厅继煎饼店和餐厅点合并之后,又有了新的成员:咖啡厅,它用于提供晚餐。

让我用迭代器模式解决这个问题。

咖啡菜单类:

//咖啡菜单
public class CafeMenu implements Menu {
	
	//使用HashMap存储
	HashMap<String, MenuItem> menuItems = new HashMap<String, MenuItem>();
  
	public CafeMenu() {
		addItem("Veggie Burger and Air Fries",
			"Veggie burger on a whole wheat bun, lettuce, tomato, and fries",
			true, 3.99);
		addItem("Soup of the day",
			"A cup of the soup of the day, with a side salad",
			false, 3.69);
		addItem("Burrito",
			"A large burrito, with whole pinto beans, salsa, guacamole",
			true, 4.29);
	}
 
	//添加菜品
	public void addItem(String name, String description, 
	                     boolean vegetarian, double price) 
	{
		MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
		menuItems.put(menuItem.getName(), menuItem);
	}
  
	/*
	 * 在这里实现了createIterator方法。
	 * 注意:我们不是取得HashMap整个的迭代器( 整个的获取方式:entrySet().iterator() )
	 * 而是取得值那部分的迭代器
	 */
	@Override
	public Iterator<MenuItem> createIterator() {
		//values方法获得menuItems值的集合
		return menuItems.values().iterator();
	}
}

修改女招待员:

//女招待员
public class Waitress {
	Menu pancakeHouseMenu;
	Menu dinerMenu;
	Menu cafeMenu; //咖啡菜单
 
	public Waitress(Menu pancakeHouseMenu, Menu dinerMenu, Menu cafeMenu) {
		this.pancakeHouseMenu = pancakeHouseMenu;
		this.dinerMenu = dinerMenu;
		this.cafeMenu = cafeMenu;
	}
 
	public void printMenu() {
		Iterator<MenuItem> pancakeIterator = pancakeHouseMenu.createIterator();
		Iterator<MenuItem> dinerIterator = dinerMenu.createIterator();
		Iterator<MenuItem> cafeIterator = cafeMenu.createIterator();

		System.out.println("MENU\n----\nBREAKFAST");
		printMenu(pancakeIterator);
		System.out.println("\nLUNCH");
		printMenu(dinerIterator);
		System.out.println("\nDINNER");
		printMenu(cafeIterator);
	}
 
	//打印菜单
	private void printMenu(Iterator<MenuItem> iterator) {
		while (iterator.hasNext()) {
			MenuItem menuItem = iterator.next();
			System.out.print(menuItem.getName() + ", ");
			System.out.print(menuItem.getPrice() + " -- ");
			System.out.println(menuItem.getDescription());
		}
	}
}

测试程序:

public class MenuTestDrive {
	public static void main(String args[]) {
		
		PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
		DinerMenu dinerMenu = new DinerMenu();
		CafeMenu cafeMenu = new CafeMenu();
 
		//构造女招待员
		Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu, cafeMenu);
		//打印菜单
		waitress.printMenu();
	}
}

输出结果:

MENU
----
BREAKFAST
K&B's Pancake Breakfast, 2.99 -- Pancakes with scrambled eggs, and toast
Regular Pancake Breakfast, 2.99 -- Pancakes with fried eggs, sausage
Blueberry Pancakes, 3.49 -- Pancakes made with fresh blueberries, and blueberry syrup
Waffles, 3.59 -- Waffles, with your choice of blueberries or strawberries

LUNCH
Vegetarian BLT, 2.99 -- (Fakin') Bacon with lettuce & tomato on whole wheat
BLT, 2.99 -- Bacon with lettuce & tomato on whole wheat
Soup of the day, 3.29 -- Soup of the day, with a side of potato salad
Hotdog, 3.05 -- A hot dog, with saurkraut, relish, onions, topped with cheese
Steamed Veggies and Brown Rice, 3.99 -- Steamed vegetables over brown rice
Pasta, 3.89 -- Spaghetti with Marinara Sauce, and a slice of sourdough bread

DINNER
Soup of the day, 3.69 -- A cup of the soup of the day, with a side salad
Veggie Burger and Air Fries, 3.99 -- Veggie burger on a whole wheat bun, lettuce, tomato, and fries
Burrito, 4.29 -- A large burrito, with whole pinto beans, salsa, guacamole

7.设计分析

我们将女招待员解耦:

我们让女招待员更具扩展性:

8.迭代器与集合

我们所使用的这些类都属于Java Collection接口的一部分。它们是一群类和接口,这其中包括了ArrayList、Vector、LinkedList、Stack和PriorityQueue。

Collection和Iterator的好处在于,每个Collection知道如何创建自己的Iterator,只要调用ArrayList的Iterator方法,就可以返回一个具体的迭代器,而我们不需要知道或者关心底层的工作方式。

HashMap对于迭代器的支持是间接的,因为它是由多个key-value构成的,我们遍历元素时,当然先要取得HashMap的所有value的集合,然后拿到value的集合的迭代器。

Java5的迭代器和集合

Java5中所有集合都新增了对遍历的支持,所以我们甚至不再需要请求迭代器了。

Java5中新增foreach语句,可以用来遍历集合或者数组,并且无需显示的创建迭代器。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

琴瘦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值