What is the difference between a state machine and the implementation of the state pattern?

前端 未结 6 1067
無奈伤痛
無奈伤痛 2020-12-24 05:41

I wonder if a state machine is just the state pattern at work or if there is actually a difference between those two?

I found this article with the

6条回答
  •  悲&欢浪女
    2020-12-24 06:29

    In case anyone still interested, here is my view:

    In state machine, the object can be in different states, but we don't really care how they behave in those states. In fact, we only care what action is applied when the object is transitioned to the next state. If you implement a state machine in Java, a state will be just an enum, or a String and there will be a Transition class with doAction() method.

    On the other hand, in state pattern, you don't really care about the transition, but how the object behave in those states. The transition is just an implementation details to make your state behaviors decoupled from each other. Each state will be a separate class, having doAction() method of its own.

    Saying state pattern makes state machine obsolete is incorrect. State pattern will be useful if the behavior of each state is important, e.g in game programming, where an object can have states like "idle", "attack", "run" and in each state you want to implement the behavior of the object.

    But for use case like ordering online products, where you don't care how the order object behaves. You only care if the order is in "added_to_cart" state, when a "payment_finished" event is published, then change it to "processing" state. In this case state is a simple enum property of the Order class, thus using state machine is much better.

提交回复
热议问题