实物类
下面以vending machine为例
5C
- Clarify
- What
- 输入输出是什么?
- 大小是否有限制? 无
- What items does this vending machine sell? coke、sprite、mountain dew
- What to do when an item sold out?
- What are the supposed payment methods? 可以使用strategy design Pattern,不同的付款方式调用不同的接口。此处假设只接受硬币
- How
- how to select items to purchase?
- What
- Core object
- Use Cases
- select item
- insert coin
- execute transaction
- cancel transaction
- refill items
- classes
- select item
- 使用
Map<String, Item> itemIdentifiers
对应按键和饮料。但是这样有个漏洞,就是可能A1按键对应的Item已经卖光了,这样就会导致NullPointerException的错误。要避免这样的问题,我们可以增加一个ItemInfo的类,然后在VendingMachine中增加一个Map<ItemInfo, List<Item>> items; Map<String, ItemInfo> itemIdentifiers;
,记录这个按键的信息,Item的信息以及剩余量
- 使用
- insert coin
void insertCoins(List<Coin> coins)
- execute transaction
- get the current selected item:
ItemInfo currentSelection;
- compare the item price ans inserted coins:
List<Coin> currentCoins;
- if not enough money, throw an exception:
- else, return the item purchased:
Item executeTransaction();
- refund if any: 上面的函数返回值只是Item,但是可能存在要找零的情况,可以将上面的函数修改为:
Pair<Item, List<Coin>> executeTransaction(); List<Coin> refund();
- get the current selected item:
- cancel transaction
- return the current coins that has been inserted.
List<Coin> cancelTransaction();
- return the current coins that has been inserted.
- refill items
void refillItems(List<Item> items);
更新Map
bad:
good:无论stock的结构有多么复杂,这样设计都可以避免暴露在vending machine中;这样设计也更方便去maintain
- select item