简体   繁体   中英

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. 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?

Is there a better design that is in compliance with Liskov and keeps the user from calling invalid methods for a specific state?

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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