咱們不單單要支持多個菜單,甚至還要支持菜單中的菜單。你如何處理這個新的設計需求? 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
設計