状态模式是一种行为模式,允许对象在其内部状态发生变化时改变其行为。该对象似乎会更改其类别。
我们正在开发自动售货机系统。这是显示自动售货机工作流程的图表。

如果你学过计算机科学,你可能会注意到它看起来像有限自动机(如果你不知道什么是 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
}
}
你能发现问题吗?
那么,我们如何解决这些问题呢?我们将把每个状态变成一个对象,然后实现表示从该特定状态(对象)进行状态转换的方法。

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

这个结构让你想起另一种模式吗?是的,这个类图基本上与策略模式相同,但它们的意图不同。我们稍后再讨论。
// declare all possible state transition methods
public 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 -> HasMoney
SUCCESS: HasMoney -> Idle
-- Customer insert money and buy a drink --
SUCCESS: Idle -> HasMoney
SUCCESS: HasMoney -> DrinkSold
Customer grab a drink
SUCCESS: DrinkSold -> Idle
VendingMachine {currentState: Idle, stocks: 1}
-- Customer insert money and buy a drink --
SUCCESS: Idle -> HasMoney
SUCCESS: HasMoney -> DrinkSold
Customer grab a drink
SUCCESS: DrinkSold -> OutOfStock
VendingMachine {currentState: OutOfStock, stocks: 0}
-- Customer insert money --
ERROR: no state transition occurs
-- Owner is going to refill drinks --
SUCCESS: OutOfStock -> Idle
VendingMachine {currentState: Idle, stocks: 2}
您可以在这里查看所有设计模式的实现。
github 存储库
以上就是状态模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号