什么是状态模式?
状态模式是一种行为模式,允许对象在其内部状态发生变化时改变其行为。该对象似乎会更改其类别。
什么时候使用它?
当您的对象的行为根据其当前状态而有所不同时,请使用状态模式。当您想要实现表示有限自动机的系统时,请使用状态模式。
问题
我们正在开发自动售货机系统。这是显示自动售货机工作流程的图表。

如果你学过计算机科学,你可能会注意到它看起来像有限自动机(如果你不知道什么是 fa,不用担心,你不需要知道它来理解状态模式)。图中,圆圈代表状态,箭头代表状态交易。
无论如何,让我们开始编写我们的第一个版本的系统。
public class vendingmachine { // vending machine has four states final static int out_of_stock = 0; final static int idle = 1; final static int has_money = 2; final static int drink_sold = 3; // when vending machine is placed, it has no drink stocks int state = out_of_stock; // our initial state int stocks = 0; public vendingmachine(int stocks) { this.stocks = stocks; if (stocks > 0) { state = idle; } } public void insertmoney() { if (state == out_of_stock) { system.out.println("error: drink is out of stock"); } else if (state == idle) { system.out.println("success: you inserted money"); state = has_money; } else if (state == has_money) { system.out.println("error: you already inserted money, you can buy now"); } else if (state == drink_sold) { system.out.println("error: please wait, we're dispensing you a drink that you bought"); } } public void pressbuybutton() { // if statements for each states } public void presscancelbutton() { // if statements for each states } public void dispensedrink() { // if statements for each states } public void refill() { // if statements for each states }}
你能发现问题吗?
这段代码违反了开闭原则。此代码违反了单一责任原则。此代码没有封装变化的内容。状态转换并不显式,它们被放置在条件语句下。如果添加其他状态或状态转换,可能会导致已经工作的代码出现错误。
解决方案
那么,我们如何解决这些问题呢?我们将把每个状态变成一个对象,然后实现表示从该特定状态(对象)进行状态转换的方法。

Melodrive
Melodrive -一个AI音乐引擎,根据用户的情绪状态和喜好生成个性化的音乐。
49 查看详情
客户
客户端与自动售货机交互。
自动售货机
这个类拥有多个状态。通过引入state接口,依赖于接口而不是实现。
状态
为所有concretestate提供通用接口。
具体状态
每个状态事务根据状态有不同的行为。例如,idle 类中定义的 insertmoney 方法和 outofstock 状态下的方法的行为不同。
现在,vendingmachine 中的许多 if 语句被删除,并且状态转换是显式的(您将在实现中看到这一点)。
结构

这个结构让你想起另一种模式吗?是的,这个类图基本上与策略模式相同,但它们的意图不同。我们稍后再讨论。
java实现
// declare all possible state transition methodspublic interface state { void insertmoney(); void pressbuybutton(); void presscancelbutton(); void dispensedrink(); void refill(int stocks);}
public class drinksold implements state { vendingmachine machine; public drinksold(vendingmachine machine) { this.machine = machine; } @override public void insertmoney() { system.out.println("error: no state transition occurs"); } @override public void pressbuybutton() { system.out.println("error: no state transition occurs"); } @override public void presscancelbutton() { system.out.println("error: no state transition occurs"); } @override public void dispensedrink() { machine.customertakesdrink(); if (machine.getstocks() > 0) { system.out.println("success: drinksold -> idle"); machine.setstate(machine.getidle()); } else { system.out.println("success: drinksold -> outofstock"); machine.setstate(machine.getoutofstock()); } } @override public void refill(int stocks) { system.out.println("error: no state transition occurs"); }}
我将跳过其他具体状态,因为它们很相似,但您可以在我的 github 存储库中查看它们(我的存储库的链接位于本博客末尾)。
public class vendingmachine { private state idle; private state hasmoney; private state drinksold; private state outofstock; private state currentstate; int stocks = 0; public vendingmachine(int stocks) { idle = new idle(this); hasmoney = new hasmoney(this); drinksold = new drinksold(this); outofstock = new outofstock(this); this.stocks = stocks; if (stocks > 0) { currentstate = idle; } else { currentstate = outofstock; } } // state transition methods, actual implementation is delegated to concrete states public void insertmoney() { currentstate.insertmoney(); } public void pressbuybutton() { currentstate.pressbuybutton(); currentstate.dispensedrink(); } public void presscancelbutton() { currentstate.presscancelbutton(); } public void refill(int stocks) { currentstate.refill(stocks); } // method to be used by concrete states to move one state to another public void setstate(state state) { currentstate = state; } // helper method used when dispensing a drink on drinksold state public void customertakesdrink() { if (stocks > 0) { system.out.println("customer grab a drink"); stocks--; } } // getter for each state public state getidle() { return idle; } public state gethasmoney() { return hasmoney; } public state getdrinksold() { return drinksold; } public state getoutofstock() { return outofstock; } public int getstocks() { return stocks; } public void setstocks(int stocks) { this.stocks = stocks; } @override public string tostring() { return "vendingmachine {" + "currentstate: " + currentstate.getclass().getsimplename() + ", stocks: " + stocks + '}'; }}
public class vendingmachinetestdrive { public static void main(string[] args) { vendingmachine machine = new vendingmachine(2); system.out.println(machine); system.out.println("-- customer insert money and cancel the transaction --"); machine.insertmoney(); machine.presscancelbutton(); system.out.println("-- customer insert money and buy a drink --"); machine.insertmoney(); machine.pressbuybutton(); system.out.println(machine); system.out.println("-- customer insert money and buy a drink --"); machine.insertmoney(); machine.pressbuybutton(); system.out.println(machine); system.out.println("-- customer insert money --"); machine.insertmoney(); system.out.println("-- owner is going to refill drinks --"); machine.refill(2); system.out.println(machine); }}
输出:
VendingMachine {currentState: Idle, stocks: 2}-- Customer insert money and cancel the transaction --SUCCESS: Idle -> HasMoneySUCCESS: HasMoney -> Idle-- Customer insert money and buy a drink --SUCCESS: Idle -> HasMoneySUCCESS: HasMoney -> DrinkSoldCustomer grab a drinkSUCCESS: DrinkSold -> IdleVendingMachine {currentState: Idle, stocks: 1}-- Customer insert money and buy a drink --SUCCESS: Idle -> HasMoneySUCCESS: HasMoney -> DrinkSoldCustomer grab a drinkSUCCESS: DrinkSold -> OutOfStockVendingMachine {currentState: OutOfStock, stocks: 0}-- Customer insert money --ERROR: no state transition occurs-- Owner is going to refill drinks --SUCCESS: OutOfStock -> IdleVendingMachine {currentState: Idle, stocks: 2}
陷阱
状态模式最终往往会拥有很多类,因为存在的类就会有尽可能多的类。如果某些状态几乎相同,您可以将它们组合在一起。这样,我们减少了重复代码,但违反了单一责任原则,请记住,当您使用状态模式时,它们是权衡的。如果一个状态有多个可达状态,实现起来会比较复杂。
与策略模式的比较
它们都允许对象通过组合和委托来合并不同的行为。在策略模式中,“客户端”在运行时更改对象的行为。另一方面,在状态模式中,“上下文”根据明确定义的状态转换方法来改变状态。
您可以在这里查看所有设计模式的实现。
github 存储库
以上就是状态模式的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/946828.html
微信扫一扫
支付宝扫一扫