咱们不单单要支持多个菜单,甚至还要支持菜单中的菜单。你如何处理这个新的设计需求? P355
java
P354
UnsupportedOperationException
instanceof
判断当前项是菜单仍是菜单项容许你将对象组合成树形结构来表现”总体/部分“层次结构。组合能让客户以一致的方式处理个别对象以及对象组合。
git
特色github
P357
P367
空迭代器:空对象(命令模式中提到过)的一个例子。空迭代器, hasNext()
永远返回 false
, next()
永远返回 null
(我的以为能够抛出 NoSuchElementException
), remove()
永远抛出 UnsupportedOperationException
。 P372
ide
public class Waitress { MenuComponent allMenus; public Waitress(MenuComponent allMenus) { this.allMenus = allMenus; } public void printMenu() { allMenus.print(); } public void printVegetarianMenu() { Iterator iterator = allMenus.createIterator(); System.out.println("\nVEGETARIAN MENU\n----"); while (iterator.hasNext()) { MenuComponent menuComponent = (MenuComponent)iterator.next(); try { if (menuComponent.isVegetarian()) { menuComponent.print(); } } catch (UnsupportedOperationException e) {} } } }
printVegetarianMenu()
方法中只有菜单项的 print()
方法能够被调用,绝对不能调用菜单(组合)的 print()
方法。你能说出缘由吗? P373
this
print()
,则一定会重复打印某些叶节点。配对下列模式和描述: P379
策略模式:封装可互换的行为,并使用委托决定使用哪个
适配器模式:改变一个或多个类的接口
迭代器模式:提供一个方式来遍历集合,而无须暴露集合的实现
外观模式:简化一群类的接口
组合模式:客户能够将对象的集合以及个别的对象一视同仁
观察者模式:当某个状态改变时,容许一群对象能被通知到idea
本文首发于公众号:满赋诸机(点击查看原文) 开源在 GitHub :reading-notes/head-first-design-patterns
设计