在实际开发中,订单往往包含订单状态,用户每次操作都要切换相应的状态,每次切换判断当前状态都是必要的,难免会引入一系列判断语句。为了让代码更清晰直观,我们引入了今天的主角国家模式。
[En]
In actual development, orders often contain order status, and users have to switch the corresponding state every time they perform an operation, and each switch to judge the current state is necessary, so it is inevitable to introduce a series of judgment statements. In order to make the code more clear and intuitive, we introduce today's protagonist-state mode.
一、概念理解
假设订单状态为下单、发货、确认收货。如果用户确认收货,则需要在常规编程中判断当前用户的状态,如果使用状态模式,则修改状态。
[En]
Suppose the order status is, place the order, deliver the goods, and confirm the receipt of the goods. If the user confirms the receipt of the goods, it is necessary to judge the status of the current user in regular programming, and then modify the status, if the status mode is used.
将每个状态抽象为一个状态类,如订单状态类、发货状态类、确认接收类,处理相应的逻辑,控制状态类中的下一个状态,定义环境类,定义初始状态,控制切换状态。
[En]
Abstract each state into a state class, such as order status class, shipping status class, confirmation receiving class, handle the corresponding logic and control the next state in the status class, define an environment class, define the initial state, and control the switching state.
在状态模式中应该包含着三个角色:
环境类(Context)角色:也称为上下文,它定义了客户端需要的接口,内部维护一个当前状态,这个类持有State接口,负责保持并切换当前的状态。
抽象状态(State)角色:定义一个接口,用以封装环境对象中的特定状态所对应的行为,可以有一个或多个行为。
具体状态(Concrete State)角色:实现抽象状态所对应的行为,并且在需要的情况下进行状态切换。
下面是状态模式的类图,看起来很直观,很容易理解。我们需要解释的是,状态模式的类图与策略模式的类图相同,但编写状态模式比编写策略模式更难。
[En]
The following is the class diagram of the state pattern, which looks intuitive and easy to understand. We need to explain that the class diagram of the state pattern is the same as the class diagram of the policy pattern, but it is more difficult to write the state pattern than the policy pattern.