(资料图片)
为了更好地理解状态模式的实现,我们可以以一个简单的售货机为例。假设有一个售货机,它有三种状态:待机状态(IdleState)、售出状态(SoldState)和赠品状态(WinnerState)。当用户投入硬币时,售货机会根据当前状态的不同做出相应的响应。
下面是状态模式的具体实现。
我们定义一个VendingMachine类作为上下文类,它包含一个状态对象和一个状态切换方法。
public class VendingMachine { private State currentState; private int count; public VendingMachine(int count) { this.count = count; currentState = new IdleState(this); } public void setCurrentState(State currentState) { this.currentState = currentState; } public void insertCoin() { currentState.insertCoin(); } public void pressButton() { currentState.pressButton(); } public void dispense() { currentState.dispense(); } public int getCount() { return count; } public void setCount(int count) { this.count = count; }}
在VendingMachine类中,我们定义了一个当前状态对象currentState和一个商品数量count。在VendingMachine类的构造函数中,我们将当前状态设置为待机状态(IdleState)。VendingMachine类还定义了一些方法,包括状态切换方法setCurrentState()、插入硬币方法insertCoin()、按下按钮方法pressButton()、发放商品方法dispense()和获取商品数量方法getCount()。
标签:
中新网5月24日电 据上海卫健委官方微信消息,2022年5月23日0—24时,上海新增本土新冠肺炎确诊病例58例和无症状感染者422例,其中39例确诊
“云健身”热背后的冷思考 国务院办公厅近日印发《“十四五”国民健康规划》,针对人民群众生命安全和身体健康事业做出诸多重要部署,其中,...
中国天气网讯 北京今天(5月24日)晴转阴,最高气温34℃;傍晚至夜间雷雨大风来袭,阵风7至8级,需注意防范。明天,北京最高气温将降至30℃
“全程网办”进一步畅通残疾人两项补贴申领渠道 实现补贴申领“一次都不跑” 本报记者 蒲晓磊 得益于残疾人两项补贴申请“跨省通办”的运行...