Java设计模式--状态模式

2018-05-12  本文已影响0人  留给时光吧

和策略模式很类似,只不过策略模式是通过替换的方式改变类的功能,状态模式则是通过改变类的状态修改类的功能。简单实现

状态接口

interface State {
    void next();
    void pre();
}

具体状态:

public class PowerOnState implements State{
    @Override
    public void next() {
        System.out.println("上一个...");
    }

    @Override
    public void pre() {
        System.out.println("下一个...");
    }


}

 */
public class PowerOffState implements State{

    @Override
    public void next() {

    }

    @Override
    public void pre() {

    }


}

环境类(对外提供接口并保存状态)

public class Player {
    private State state;

    public void setState(State state) {
        this.state = state;
    }

    public void next() {
        state.next();
    }

    public void pre() {
        state.pre();
    }

    public void powerOff() {
        state = new PowerOffState();
        System.out.println("关机了");
    }

    public void powerOn() {
        state = new PowerOnState();
        System.out.println("开机了");
    }
}

测试类


    public static void main(String[] args) {
        Player player = new Player();
        player.powerOn();
        player.next();
        player.powerOff();
        player.next();
    }
上一篇 下一篇

猜你喜欢

热点阅读