Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我们不能只写一些 play() stop() pause() 函数吗? 使用状态机执行此操作有什么好处?
您的情况的主要优点是每个状态都确定哪些操作是有效的以及状态机如何对它们做出反应。
在一个非常简单的模型中,您的状态机将具有状态
这些状态中的每一个都定义了哪些操作是有效的。允许在Playing状态下调用 Play() 是没有意义的。允许 Stop() 处于Not Playing状态也是没有意义的。状态机可帮助您确定哪些操作在哪个状态下有效。
顺便说一句:每个程序都是一种状态机,但并非每个程序都以状态机为模型。通过创建模型,您的代码会自动变得更有条理并提高可读性。