设计形式-行为模式-状态模式-Java
设计模式--行为模式--状态模式--JavaStateIntent?Allow an object to alter its behavior when its intern
设计模式--行为模式--状态模式--Java
StateIntent
?Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
applicabilityAn object's behavior depends on its state, and it must change its behavior at run-time depending on that state.
Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants.Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects.UML
下面摘自《Java与模式》:
Game Engine example作为一个通用的游戏,站在抽象的角度来讲,实际上可以简单分为,菜单屏,游戏屏,设置屏,帮助屏。
状态图
通过状态图可以发现,实际上这几种状态有明显的状态的变迁。每一种状态对应其自身的渲染过程,以及事件处理过程。
经过抽象可以得到下列对象模型
Screen.update主要作用为处理事件响应,譬如鼠标键盘触屏等。Screen.present主要作用渲染当前状态的帧。
下面这个类是较为简单的HelpScreen代码:
game.getCurrentScreen().update(detaltime);// update current screengame.getCurrentScreen().present(detaltime);// present current screen
第一个更新当前State事件第二个更新当前State帧
假如说这里根本不使用State Patterns,可以想象一下,首先会出现switch过多这种情况(代码坏味道),对于渲染需要switch对于事件更新也需要switch,而且这些代码极大的可能和渲染高度偶合在一起,假如需求变更,需要添加商铺功能,高分功能,这个时候不可避免阅读代码困难,修改不易。
综上所述,通过使用State Patterns可以解耦状态调用端和状态变迁端,即游戏渲染线程和Screen变迁。另一方面,对于状态的添加开放,对现有状态修改关闭,符合OCP原则,另一方面也符合SRP原则。