更改状态时获得附加内容的正确方法是什么

What is the proper way to have additional content when changing state

我有一个这样的 class :

public class Machine {
    enum State {
        STARTED, STOPPED
    }

    private State state;
    private String whyIsItStopped; // only used in STOPPED state

    ...
}

我想知道执行此操作的正确方法是什么。我有一个更复杂的方法class,如果我这样做,它似乎是一团糟。

问题出在我的架构上,你能给我一些建议吗?

更新

使用状态模式,我得到了一个类似的解决方案:

public interface State {

    public String whyIsItStopped();

    public class Started implements State {
        @Override
        public String whyIsItStopped() {
            return null;
        }
    }

    public class Stopped implements State {
        private final String reason;

        public Stopped(String reason) {
            this.reason = reason;
        }

        @Override
        public String whyIsItStopped() {
            return reason;
        }
    }
}

public class Machine {

    private State state = new State.Started();

    public String whyIsItStopped(){
        state.whyIsItStopped();
    }

    // setState etc ...
}

状态模式似乎可以很好地改变同一方法的行为,但对于其他字段/数据来说却很奇怪。

问题是它不是真正的同一个对象,多态性不可能真正有用。 我必须在获取其内容之前测试机器是否已停止(作为 instanceof 的方式)

if (machine.isStopped()){
     println(machine.whyIsItStopped());
}

另一种方法可能是仅在 Stopped 状态下设置 getter

public interface State {

    public class Started implements State {}

    public class Stopped implements State {
        private final String reason;

        public String whyIsItStopped() {
            return reason;
        }
    }
}

并检索消息:

if (machine.isStopped()){
    println(((State.Stopped)machine.getState()).whyIsItStopped());
}
// Yeah that's not really beautiful

无论是在架构上还是在使用上都很奇怪。

你有比 instanceof 更好的解决方案吗?

您的问题似乎很明显 State Pattern。它将允许您实现一个可以使用新状态进行扩展而无需修改现有代码的解决方案。

The state pattern is a behavioral software design pattern that implements a state machine in an object-oriented way. With the state pattern, a state machine is implemented by implementing each individual state as a derived class of the state pattern interface, and implementing state transitions by invoking methods defined by the pattern's superclass.