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

ham*_*ini 3 java oop design-patterns object-composition implements

在这里阅读此链接,在此处输入链接描述,以了解State Desing Patern.

接口类:

public interface State {
    void doAction();
}
Run Code Online (Sandbox Code Playgroud)

onState类:

public class TVStartState implements State {

    @Override
    public void doAction() {
        System.out.println("TV is turned ON");
    }
}
Run Code Online (Sandbox Code Playgroud)

截止态:

public class TVStopState implements State {

    @Override
    public void doAction() {
        System.out.println("TV is turned OFF");
    }

}
Run Code Online (Sandbox Code Playgroud)

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

测试类:

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();

}
Run Code Online (Sandbox Code Playgroud)

现在我有两个问题:

1-为什么TVContext Class implementsState并且还有Composition什么?是OO中的错误?因为例如 Cat从Animal类继承并且has_a动物在一起(在这种情况下).

2-If此TestClass中的最终程序员将上下文传递给 context.setState()而不是tvStartStatetvStopState,程序成功编译但在run_time中出错. 在此输入图像描述

对于State Design Pattern中的第二个问题 ,same name method可以使用而不是继承.但int 装饰设计模式没有.

小智 8

  1. 为什么TVContext类实现State并具有组合?

示例不正确,TVContext不应实现接口State.从State Design Pattern的UML图中我们可以看到该类Context只构成一个实现接口的属性State.

状态设计模式的UML图

  1. 如果在此TestClass中通最终程序员背景下,以context.setState()代替tvStartStatetvStopState,程序编译成功,但在RUN_TIME错误.

它编译的原因是因为上下文正在实现接口State,但它在运行时失败,java.lang.StackOverflowError因为函数context.setState()在没有退出条件的情况下以递归方式调用自身.StateTVContext类中删除接口可以解决此问题.

Decorator Design Pattern中,目的是向Component类添加新行为.这就是继承用于向Component添加新方法的原因.

State Design Pattern中,目的是更改Context类的行为.例如,如果我们使用带有抽象类而不是接口的继承来实现它,则对具体状态类的操作需要覆盖抽象类中定义的操作.这就是为什么界面在这种情况下更有意义.