设计模式:恢复状态&手术

时间:2017-08-28 11:52:15

标签: object design-patterns

恢复状态和状态的好方法是什么?对象的操作?

例如,当转换到特定状态时,对象将需要执行某个操作。

问题在于直接通过对象构造函数恢复状态:在构造函数中执行操作不是一个好习惯。所以在这一点上,只恢复了状态,而不是操作。

enum State { OPEN, CLOSED }

class Stuff {

    State state;
    Timer timer;
    Counter counter;

    Stuff(State state, Timer timer, Counter counter) {
        this.state = state;
        this.timer = timer;
        this.counter = counter;

        // It is not a good idea to call timer.start() here when the state = OPEN.
    }

    void open() {
        state = OPEN;
        timer.start();
        counter.reset();
    }

    void close() {
        state = CLOSED;
    }

}

恢复对象操作时,我们不能简单地调用open。因为counter将被重置并失去其初始值(构造函数中提供的值)。

0 个答案:

没有答案