简体   繁体   English

符合 Liskov 的状态设计模式

[英]State design pattern in compliance with Liskov

I am designing an order system and the state design pattern seems appropriate because the order can change its state and thereby the allowed functionalities for the order.我正在设计一个订单系统,状态设计模式似乎很合适,因为订单可以更改其状态,从而可以更改订单允许的功能。 Below is my basic class diagram:下面是我的基本类图:

I do not like this approach because clients cannot see if a method is supported and violates Liskov principle.我不喜欢这种方法,因为客户无法看到某个方法是否受支持并且违反了 Liskov 原则。 I created an alternative below:我在下面创建了一个替代方案:

I like this better but still the client has to check if a method is supported.我更喜欢这个,但客户端仍然必须检查是否支持一种方法。 But they can still call the unsupported method and get an exception.但是他们仍然可以调用不受支持的方法并获得异常。 Does this still violates the Liskov principle?这是否仍然违反 Liskov 原则?

Is there a better design that is in compliance with Liskov and keeps the user from calling invalid methods for a specific state?是否有更好的设计符合 Liskov 并防止用户调用特定状态的无效方法?

What you are showing is not State pattern.你展示的不是状态模式。 State pattern alters object behavior when its internal state changes.状态模式在其内部状态改变时改变对象行为。 For example, a light switch can turn on or turn off the light when you toggle it, depending on its state (different behavior on the same method).例如,当您切换灯时,灯开关可以打开或关闭灯,具体取决于其状态(同一方法的不同行为)。

With this Order interface (4 diff methods) I don't see any benefits of introducing State pattern.使用此 Order 接口(4 种差异方法),我看不到引入状态模式的任何好处。 It will only complicate things for no reason.它只会无缘无故地使事情复杂化。 But I don't know all the details so it is up to you what to do next.但我不知道所有细节,所以接下来要做什么取决于你。

Check this link to see examples of State patten implementation https://sourcemaking.com/design_patterns/state检查此链接以查看状态模式实施的示例https://sourcemaking.com/design_patterns/state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM