您当前的位置:首页 >> 大数据 >  正文
设计模式-状态模式(二)
来源: 腾讯云      时间:2023-05-05 18:29:39


【资料图】

状态模式的示例

为了更好地理解状态模式的实现,我们可以以一个简单的售货机为例。假设有一个售货机,它有三种状态:待机状态(IdleState)、售出状态(SoldState)和赠品状态(WinnerState)。当用户投入硬币时,售货机会根据当前状态的不同做出相应的响应。

下面是状态模式的具体实现。

上下文(Context)

我们定义一个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()。

X 关闭

X 关闭