状态模式是指游戏角色的状态切换等情况使用到的状态变化模式。
类的行为是根据类的状态变化的,在状态模式中,我们创建各种状态对象和一个行为根据状态对象变化的context类。
比如我们玩一款动作游戏,当我们开大招变身是我,我们的技能行为会有所改变,这只是在角色内部控制部分改变状态对象,外部与玩家的沟通模式不发生改变。当状态对象更新到另一个类时,对象就会根据新的状态类展示新的行为,这一切只是发生在对象内部,玩家不需要知道过程是怎么运作的。
经典状态模式:
Context类
public void Context(){
State states = null;
public void show(int value){
states.skills(value);
}
public void setState(State thisState){
this.states = thisState;
}
State类
public abstract class State{
protected Context context = null;
public State (Context theContext){
this.context = theContext;
}
public abstract void skills(int value);
State子类
public class StateA : State{
public StateA (Context theContext) :base(theContext)
{}
public override void skills(int value){
//skills
if(value>=10){
context.setState(new StateB(context));
}
}
测试用例
void unitState (){
Context theContext = new Context();
theContext.setState(new StateA(theContext));
theContext.show(5);
theContext.show(12);
theContext.show(7);
改变状态
改变状态有两种方式
1、context对象自己按照条件更改状态
2、创建一个context对象,传入state对象,在每个状态对象内部进行状态更新。
第二种明显优于第一种,不至于context类过于臃肿,每个state对象都有相对独立的属性,更好维护。