我阅读了这个链接 enter link description here , 学习状态设计模式。
接口(interface)类:
public interface State {
void doAction();
}
onState 类:
public class TVStartState implements State {
@Override
public void doAction() {
System.out.println("TV is turned ON");
}
}
关闭状态:
public class TVStopState implements State {
@Override
public void doAction() {
System.out.println("TV is turned OFF");
}
}
TvContext 类:
public class TVContext implements State {
private State tvState;
public void setState(State state) {
this.tvState=state;
}
public State getState() {
return this.tvState;
}
@Override
public void doAction() {
this.tvState.doAction();
}
}
测试类:
public static void main(String[] args) {
TVContext context = new TVContext();
State tvStartState = new TVStartState();
State tvStopState = new TVStopState();
context.setState(tvStartState);
context.doAction();
context.setState(tvStopState);
context.doAction();
}
现在我有两个问题:
1- 为什么 TVContext 类 implements
State 和 Composition
在一起?
是 OO 中的错误吗?
因为例如 Cat 继承自 Animal 类并且有一个动物在一起(在这种情况下)。
2-如果此 TestClass 中的最终程序员将 context 传递给 context.setState()
而不是 tvStartState 或 tvStopState ,程序编译成功但运行时出错。
对于State Design Pattern中的第二题,可以用同名方法
代替继承。但 int Decoration Design Pattern 不是。
最佳答案
- 为什么
TVContext
类实现了State
并且组合在一起?
示例不正确,TVContext
不应该实现接口(interface) State
。从状态设计模式的 UML 图我们可以看到类 Context
只有
组成一个实现接口(interface) State
的属性。
- 如果此 TestClass 中的最终程序员将 context 传递给
context.setState()
而不是 tvStartState 或 tvStopState , 程序编译成功但运行时出错。
它编译的原因是因为 context 正在实现接口(interface) State
,但它在运行时失败并出现 java.lang.StackOverflowError
因为函数 context.setState()
在没有退出条件的情况下递归调用自身。从 TVContext
类中删除接口(interface) State
可解决此问题。
在Decorator Design Pattern 中,目的是向Component 类添加新的行为。这就是为什么使用继承来向 Component 添加新方法的原因。
在状态设计模式中,目的是改变Context类的行为。例如,如果我们使用抽象类而不是接口(interface)的继承来实现它,那么对具体状态类的操作需要覆盖抽象类中定义的操作。这就是为什么接口(interface)在这种情况下更有意义。
关于java - 在状态设计模式中使用组合和实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53994807/