ood解题思路----实物类面向对象

文章介绍了如何设计一个自动售货机(VendingMachine)系统,包括使用Map存储商品信息,使用ItemInfo记录商品状态和库存,以及处理插入硬币(insertCoin)、执行交易(executeTransaction)、取消交易(cancelTransaction)和补货(refillItems)的逻辑。特别提到了当商品售罄或找零情况的处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实物类

下面以vending machine为例

5C

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值