且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何正确使用状态模式?

更新时间:2023-12-03 23:23:52

@Ivan:网络上有一些资源可用于分层状态机(HSM)。 Miro Samek已经广泛地撰写了这个设计模式,并提供了大量有用的信息。

@Ivan: There are a number of resources available on the web for Hierarchical State Machines (HSM). Miro Samek has written extensively about this design pattern and offers a lot of helpful information.

应该感兴趣的一些文章:

Some articles that should be of interest:

  • State-Oriented Programming (SOP) (Samek) (pdf)
  • Hierarchical State Machines - a Fundamentally Important Way of Design (Samek) (pdf)
  • Practical State Charts in C/C++ (Samek) (link to google-books)
  • State-Oriented Programming (by Asher Sterkin) (pdf)

使用HSM o Mealy和Moore描述的平坦的FSM状态图表明,层次结构造成了责任分离。子状态只需要处理它们被明确设计处理的条件 - 未处理的事件被传递到父状态,如果父状态没有被明确设计来处理它,那么它被传递到下一个更高的父母等等。它允许您创建小型,可管理的状态机,每台机器都可以提供一个单一的目的 - 一个可以适应单个对象的状态机。随着新功能的添加,或添加新课程,他们只需要处理自己的小部分世界,并将未处理的事件传递给他们各自的父母。

The big benefit of using HSM over flat FSM state charts described by Mealy and Moore is that the hierarchy creates a separation of responsibility. Sub-states only need to handle those conditions that they are expressly designed to handle--unhandled events get passed up to the parent state, if the parent state isn't expressly designed to handle it then it is passed up to the next-higher parent and so on. It allows you to create small, manageable state machines that each serve a single purpose--one that can fit within a single object. As new features are added, or as new classes are added, they only need to handle their own little part of the world and pass on the unhandled events to their respective parents.

当正确实现时,您将获得一个具有低环路复杂度的强大的程序,这很容易根据需要进行修改或升级。

When implemented correctly, you get a robust program with low cyclomatic complexity, that is easy to modify or upgrade as needed.