📜  门| GATE-CS-2016(套装1)|第 53 题(1)

📅  最后修改于: 2023-12-03 15:42:18.426000             🧑  作者: Mango

门| GATE-CS-2016(套装1)|第 53 题

这道题目要求我们实现一个 Java 类,用于表示门 (Gate)。门有三种状态:打开 (OPEN),关闭 (CLOSED) 和故障 (FAULTY)。

解题思路

我们可以定义一个枚举类型 GateState 来表示门的状态,然后在门类中定义一个实例变量来保存当前状态。

门类要实现三个方法:

  • void open():将门从关闭状态转换为打开状态。
  • void close():将门从打开状态转换为关闭状态。
  • GateState getState():获取门当前的状态。

对于门的状态转换,我们需要检查当前状态是否允许进行转换。如果门已经处于需要转换到的状态,我们什么都不需要做。如果门处于其他状态,则需要将门状态转换到所需的状态。

代码实现
public class Gate {
    private GateState state;

    public Gate() {
        this.state = GateState.CLOSED;
    }

    public void open() {
        if (state == GateState.OPEN || state == GateState.FAULTY) {
            return;
        }
        state = GateState.OPEN;
    }

    public void close() {
        if (state == GateState.CLOSED || state == GateState.FAULTY) {
            return;
        }
        state = GateState.CLOSED;
    }

    public GateState getState() {
        return state;
    }
}

public enum GateState {
    OPEN,
    CLOSED,
    FAULTY
}
测试样例
Gate gate = new Gate();
assert(gate.getState() == GateState.CLOSED);
gate.open();
assert(gate.getState() == GateState.OPEN);
gate.open();
assert(gate.getState() == GateState.OPEN);
gate.close();
assert(gate.getState() == GateState.CLOSED);
gate.close();
assert(gate.getState() == GateState.CLOSED);
gate.state = GateState.FAULTY;
gate.open();
assert(gate.getState() == GateState.FAULTY);
gate.close();
assert(gate.getState() == GateState.FAULTY);