情况:我的状态有一个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/