状态模式实现

2018-08-26  本文已影响21人  Stroman

图示

状态模式.png

输出

正在转换状态...
转换到B状态
正在转换状态...
转换到C状态
正在转换状态...
转换到A状态
正在转换状态...
转换到B状态

Process finished with exit code 0

代码

main

package com.company;

public class Main {

    public static void main(String[] args) {
    // write your code here
        StateMachine machine = new StateMachine(new StateA());

        machine.changeState();
        machine.changeState();
        machine.changeState();
        machine.changeState();
    }
}

状态机

package com.company;

public class StateMachine {
    private State machineState;

    public StateMachine(State machineState) {
        this.machineState = machineState;
    }

    public void setMachineState(State machineState) {
        this.machineState = machineState;
    }

    public void changeState() {
        System.out.println("正在转换状态...");
        this.machineState.changeToNextState(this);
    }
}

状态的抽象接口

package com.company;

public interface State {
    void changeToNextState(StateMachine machine);
}

A状态

package com.company;

public class StateA implements State {
    @Override
    public void changeToNextState(StateMachine machine) {
        machine.setMachineState(new StateB());
        System.out.println("转换到B状态");
    }
}

B状态

package com.company;

public class StateB implements State {
    @Override
    public void changeToNextState(StateMachine machine) {
        machine.setMachineState(new StateC());
        System.out.println("转换到C状态");
    }
}

C状态

package com.company;

public class StateC implements State {
    @Override
    public void changeToNextState(StateMachine machine) {
        machine.setMachineState(new StateA());
        System.out.println("转换到A状态");
    }
}

上一篇 下一篇

猜你喜欢

热点阅读