java - 在状态设计模式中使用组合和实现

标签 java oop design-patterns implements object-composition

我阅读了这个链接 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() 而不是 tvStartStatetvStopState ,程序编译成功但运行时出错。 enter image description here

对于State Design Pattern中的第二题,可以用同名方法代替继承。但 int Decoration Design Pattern 不是。

最佳答案

  1. 为什么 TVContext 类实现了 State 并且组合在一起?

示例不正确,TVContext 不应该实现接口(interface) State。从状态设计模式的 UML 图我们可以看到类 Context 只有 组成一个实现接口(interface) State 的属性。

UML diagram for State Design Pattern

  1. 如果此 TestClass 中的最终程序员将 context 传递给 context.setState() 而不是 tvStartStatetvStopState , 程序编译成功但运行时出错。

它编译的原因是因为 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/

相关文章:

java - 如何模拟测试下方法调用的方法

java - 编写一个程序来接收用户的输入并检查其拼写

java - 无法执行目标 org.apache.maven.plugins :maven-surefire-plugin:2. 18.1:test

java - 如何在事件上调用 jquery 函数?

java - 为什么不存储对象值?

java - 动态方法调度

c++ - 多种输出格式的设计模式

c++ - 我们什么时候应该使用方法重载与具有不同命名的方法

c++ - C++单例代码解释

c# - 当表单的类变得太大时怎么办?