首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

设计形式-行为模式-状态模式-Java

2013-03-10 
设计模式--行为模式--状态模式--JavaStateIntent?Allow an object to alter its behavior when its intern

设计模式--行为模式--状态模式--Java

State

Intent

?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
下面摘自《Java与模式》:设计形式-行为模式-状态模式-Java
Game Engine example作为一个通用的游戏,站在抽象的角度来讲,实际上可以简单分为,菜单屏,游戏屏,设置屏,帮助屏。设计形式-行为模式-状态模式-Java

设计形式-行为模式-状态模式-Java

设计形式-行为模式-状态模式-Java


设计形式-行为模式-状态模式-Java

状态图
设计形式-行为模式-状态模式-Java
通过状态图可以发现,实际上这几种状态有明显的状态的变迁。每一种状态对应其自身的渲染过程,以及事件处理过程。
经过抽象可以得到下列对象模型
设计形式-行为模式-状态模式-Java
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原则。

热点排行