状态模式:从字符串中识别状态 class 类型

State pattern: Identify state class type from string

背景

我有一个使用状态模式的命令。当命令状态发生变化时,我会在 UI 中收到通知,例如 class stageOneState 现在处于活动状态。使用字符串作为标识符来检查状态 class 类型是不好的做法吗?这是在撤销状态模式的工作吗?

有什么替代方案?

例子

if (notifiedState.type == "state1") {
// Update UI accroding to state1
} else ...

例子

示例来自 http://www.tutorialspoint.com/design_pattern/state_pattern.htm

public interface State {
   public void doAction(Context context);
}

public class StartState implements State {

   public void doAction(Context context) {
      System.out.println("Player is in start state");
      context.setState(this);   
   }

   public String toString(){
      return "Start State";
   }
}

public class StopState implements State {

   public void doAction(Context context) {
      System.out.println("Player is in stop state");
      context.setState(this);   
   }

   public String toString(){
      return "Stop State";
   }
}

public class Context {
   private State state;

   public Context(){
      state = null;
   }

   public void setState(State state){
      this.state = state;       
   }

   public State getState(){
      return state;
   }
}

public class StatePatternDemo {
   public static void main(String[] args) {
      Context context = new Context();

      StartState startState = new StartState();
      startState.doAction(context);

      System.out.println(context.getState().toString());

      StopState stopState = new StopState();
      stopState.doAction(context);

      System.out.println(context.getState().toString());
   }
}
  1. 当您从外部检查对象的状态然后根据对象的状态采取不同的行动时,您就撤消了状态模式。如果它看起来更方便,那么状态可能是这项工作的错误工具。

  2. "command having a state"这句话举起了红旗。这是状态和命令模式的某种邪恶混搭吗?

  3. 示例中有一个严重的错误:您正在使用标识而不是值来比较字符串。

  4. 一般来说,如果您对任何模式有任何疑问,请不要尝试使用它。它们是有毒的动物,最好在安全距离内进行研究。

这种模式有时被称为 stringly typedstrongly typed 的双关语)。

最好的方法是使用枚举。