How to use state pattern correctly?

后端 未结 9 698
既然无缘
既然无缘 2021-01-29 21:54

I\'ve encountered a few implementations of state pattern in my programming experience, and done a few. I\'ve seen them used in various scenarios (mostly UI and parsing). The tro

9条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-29 22:09

    You should use the state pattern, if you have a different behaviour for each state. Maybe you need to reconfigure the transitions on runtime. Another reason for using it is you might have to add more states later on.

    Imagine a boardgame like Chinese Checkers you have different GUI States for picking a Pawn, select a target slot and so on. In each state the GUI should behave differently, some inputs should be handled others ignored. Using a simple switch/case is possible but state pattern comes handy as the logic is encapsulated, related code is toghether. This makes it easier to introduce new states without affecting most/all of the other states (depending on who is responsible to set the transitions: either the state knows its outgoing transitions, or they could be given at runtime e.g. using the constructor).

    As you can see in this example, the GuiController uses an IGuiState Interface to change its behaviour on demand. An implementation can be seen here.

    The main pitfall is to use switch/case, when you need to be flexible. Since the indirection takes a bit more time, I would recommend that for a fixed amount of rather simple staates. I you have to implement a rather fast low level network protocol, that is usually to much overhead.

提交回复
热议问题