Java果汁商店应用故障:剩余果汁数量未按预期递减
剩余果汁数量未正常递减的问题排查与解决
问题根源
你创建了三个独立的JuiceStore实例,每个实例都自带一份leftJuices变量(初始值3)。这意味着Juice1、Juice2、Juice3的剩余果汁计数完全分离,调用其中一个的buyJuice只会减少该实例自己的计数,而不是共享的总库存。这和你预期的"总共3份果汁,下单一次总库存减1"逻辑不符。
看JuiceStore类的定义:
private int leftJuices = 3;
这里的leftJuices是实例变量(无static修饰),每个新创建的JuiceStore对象都会重新初始化这个变量为3,三个对象之间没有任何关联。
解决方案
根据你的业务需求,有两种可行的修复方式:
方式1:让所有商店实例共享库存(静态变量)
如果需要多个JuiceStore实例共享同一批果汁库存,把leftJuices改为静态变量(类级变量):
public class JuiceStore { private int temperature; private static int leftJuices = 3; // 加static修饰,变为所有实例共享的变量 JuiceStore(int temperature) { this.temperature = temperature; } public void buyJuice() throws NoJuiceException, TooColdException, TooWarmException { if(leftJuices < 1) throw new NoJuiceException("Unfortunately, there is no juice left. Come back tomorrow."); leftJuices--; // 简化递减语句 System.out.println(); System.out.println("You have bought a juice, there are " + leftJuices + " left."); if (this.temperature < 9) throw new TooColdException("The juice is too cold."); if (this.temperature > 15)throw new TooWarmException("The juice is too warm."); System.out.println("Drink successful."); } }
这样不管创建多少个JuiceStore实例,都会共用同一个leftJuices计数,每次调用buyJuice都会减少共享库存。
方式2:使用单例商店(更符合业务逻辑)
如果你的场景是"整个应用只有一个果汁商店",那应该只创建一个JuiceStore实例,所有购买操作都调用这个实例的方法:
修改Program类的main方法:
public class Program { public static void main(String[] args) { // 只创建一个果汁商店实例 JuiceStore juiceStore = new JuiceStore(14); // 三次购买都调用同一个实例的buyJuice try { juiceStore.buyJuice(); } catch(NoJuiceException e) { System.out.println("\n" + e.getMessage()); } catch(TooColdException e) { System.out.println(e.getMessage()); } catch(TooWarmException e) { System.out.println("The juice is too warm."); } try { juiceStore.buyJuice(); } catch(NoJuiceException e) { System.out.println("\n" + e.getMessage()); } catch(TooColdException e) { System.out.println(e.getMessage()); } catch(TooWarmException e) { System.out.println(e.getMessage()); } try { juiceStore.buyJuice(); } catch(NoJuiceException e) { System.out.println("\n" + e.getMessage()); } catch(TooColdException e) { System.out.println(e.getMessage()); } catch(TooWarmException e) { System.out.println(e.getMessage()); } } }
这种方式更贴近现实中"一个商店"的逻辑,也避免了静态变量可能带来的线程安全隐患(如果后续扩展多线程下单的话)。
额外优化
buyJuice里的递减语句可以简化为this.leftJuices--;,和this.leftJuices = leftJuices-1;功能完全一致,代码更简洁。
内容的提问来源于stack exchange,提问作者not_a_nerd
相关产品推荐
相关产品推荐

