java - 状态设计模式: How to avoid code duplication when using entry() and exit()?

标签 java design-patterns code-duplication state-pattern

情况:我的状态有一个entry()和exit()方法,每次状态转换时都需要调用。为了确保这一点,我在 State 中使用了包含必要过程的 changeState() 方法。每次使用涉及状态机的操作时,上下文都会调用它。然而问题是,每次添加新方法时我都需要调用 state.changeState(),并且我确信有一种方法可以避免代码重复。下面是进一步说明的代码

class Context {
    State state;

    void method1() {
        state.method1();
        state.changeState();
    }

    void method2() {
        state.method2();
        state.changeState(); // Code duplication!!
}

abstract class State {
    Context context;
    State next;

    void changeState() {
        this.exit();
        next.entry();
        context.setState(next);
    }
    // other necessary methods
}

class ConcreteState extends State {
    void method1() {
        // do something
        next = AnotherConcreteState;
    }
    void entry() {/*do something */};
    void exit() {/*do something */};
}

如果我想在 Context 中添加其他方法,我该如何避免每次在新方法中调用 state.changeState() 的代码重复?

最佳答案

你们很接近。 changeState 方法属于 Context 类,而不是 State 类。这是a good article on the topic 。请注意,类图显示了 Document(上下文)类中的 changeState

为了使其更加清晰,changeState 可以将next 状态作为参数。像这样:

class Context {
  State state;

  void method1() {
    state.method1();
  }

  void changeState(next) {
    state.exit();
    this.state = next;
    state.enter();
  }
}

abstract class State {
  Context context;

  // other methods
}

class ConcreteState extends State {
  void method1() {
    // do something
    context.changeState(AnotherConcreteState);
  }

  void enter() { /* do something */ }
  void exit() { /* do something */ }
}

现在,当您向 Context 添加更多方法时,Context 中不会出现重复。它看起来像这样:

class Context {
  State state;

  void method1() {
    state.method1();
  }

  void method2() {
    state.method2();
  }

  void changeState(next) {
    state.exit();
    this.state = next;
    state.enter();
  }
}

abstract class State {
  Context context;

  // other methods
}

class ConcreteState extends State {
  void method1() {
    // do something
    context.changeState(AnotherConcreteState);
  }

  void method2() {
    // do something else
    context.changeState(YetAnotherConcreteState);
  }

  void enter() { /* do something */ }
  void exit() { /* do something */ }
}

关于java - 状态设计模式: How to avoid code duplication when using entry() and exit()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63245531/

相关文章:

java - 如何创建名为查询的实体

java - BufferedWriter 未写入第一行文本

Java 对象、更改的字段监听器、设计模式

python - `if __name__ == "__main_ _": ` 这样的成语有设计模式的名字吗?

c# - 包含创建实例的方法的接口(interface)

java - 类需要一个 bean,但找到了 2 个 :

java - 检查 android 模拟器是否静音

c++ - 在模板层次结构中继承类型声明

php - 如何减少 Symfony2 中的代码重复

vb.net - 任何工具来检查重复的 VB.NET 代码?