1、前言
实物类设计题目其实跟前面的管理类、预定类差不多,都是需要考虑主体、输入、输出的。自动售货机最明显的主体是 VendingMechine,input 是 Payment(此处简化为 Coin),输出是 Item。
此处有一个小 tips:针对于 Payment,有不同的实现的话,可以使用 strategy design pattern。然后需要产生策略的时候,我可以用 Factory design pattern 产生不同的策略。
还有一点需要说明的是,现实生活中,这几种 design pattern 非常实用:Singleton、Strategy、Factory。
2、设计
类图3、代码
Coin:
public enum Coin {
PENNY(1),
NICKLE(5),
DIME(10),
QUARTER(25);
private float value;
Coin(float value) {
this.value = value;
}
public float getValue() {
return value;
}
public void setValue(float value) {
this.value = value;
}
}
Item:
public class Item {
/**
* 价格
*/
private float price;
/**
* 名称
*/
private String name;
public Item(float price, String name) {
this.price = price;
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
VendingMachine:
public class VendingMachine {
/**
* 售货机保存的硬币
*/
private List<Coin> coins;
/**
* 售货机保存的商品
*/
private Map<String, List<Item>> stocks;
/**
* 当前选择的商品
*/
private Item currentSelect;
/**
* 当前投入的硬币
*/
private List<Coin> currentCoins;
public VendingMachine() {
this.coins = new ArrayList<>();
for(int i = 0; i < 10; i++){
this.coins.add(Coin.PENNY);
this.coins.add(Coin.NICKLE);
this.coins.add(Coin.DIME);
this.coins.add(Coin.QUARTER);
}
this.stocks = new HashMap<>();
for(int i = 1; i <= 4; i++){
List<Item> list = new ArrayList<>();
list.add(new Item(i, "可乐_" + i));
list.add(new Item(i, "可乐_" + i));
this.stocks.putIfAbsent("可乐_" + i, list);
}
}
public float selectItem(String selection) throws Exception {
List<Item> items = this.stocks.get(selection);
if(items == null || items.isEmpty()){
throw new Exception("没货");
}
this.currentSelect = items.get(0);
return this.currentSelect.getPrice();
}
public void insertCoins(List<Coin> coins){
this.currentCoins = coins;
}
public Pair<Item, List<Coin>> executeTrans(){
this.coins.addAll(currentCoins);
return new Pair<>(this.currentSelect, this.refund());
}
public List<Coin> cancelTrans(){
this.currentSelect = null;
List<Coin> coins = new ArrayList<>(this.currentCoins);
this.currentCoins = null;
return coins;
}
private List<Coin> refund(){
float money = 0;
for (Coin currentCoin : this.currentCoins) {
money += currentCoin.getValue();
}
float fund = money - this.currentSelect.getPrice();
// 这应该是一个零钱兑换问题,但是一般自动售卖机的话可能是正好找零,不会出现不能找的情况
return new ArrayList<>();
}
}
网友评论