状态模式:如果状态只是抛出异常或更改其状态,这仍然是一种好的设计吗?

问题描述

我正在尝试使用State模式。根据上下文所处的状态,将引发不同的错误消息或根本不发出任何错误消息。但是我不确定这是否是使用异常的正确方法。 以下是进一步说明的代码。我特意排除了修饰符。

class Context {
  State currentState;

  void changeState(State newState) {
    currenState = newState;
  }

  void operationA() {
    currentState.tryOperationA();
    // do operation A
  }
  // some more operations all with same structure but different functionality
}

abstract class State {
  Context context;

  State (Context context) {
    this.context = context;
  }

  void tryOperationA() {
    throw new IllegalStateException();
  }
  // some more tryOperation...
}

class AllowOpAState extends State {
  @Override
  void tryOperationA() {
    context.changeState(new AnotherState());
  }
}

class AnotherState extends State {
  // changes state with other operations
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)