设计模式之状态

状态模式:无非就是状态的改变
这里写图片描述

public class App {
    public static void main(String[] args) {
        Mammoth mammoth=new Mammoth();
        mammoth.observe();
        mammoth.timePasses();
        mammoth.observe();
        mammoth.timePasses();
        mammoth.observe();
    }
}
public interface State {
    void onEnterState();
    void observe();
}
public class AngryState implements State {
    private Mammoth mammoth;
    public AngryState(Mammoth mammoth){
        this.mammoth=mammoth;
    }

    @Override
    public void onEnterState() {
        System.out.println(mammoth+" 暴怒了");
    }

    @Override
    public void observe() {
        System.out.println(mammoth+" 开始生气了!");
    }
}
public class PeacefulState implements State{
    private Mammoth mammoth;
    public PeacefulState(Mammoth mammoth){
        this.mammoth=mammoth;
    }
    @Override
    public void onEnterState() {
        System.out.println(mammoth+" 冷静和安详");
    }

    @Override
    public void observe() {
        System.out.println(mammoth+" 冷静下来了");
    }
}
public class Mammoth {
    private State state;
    public Mammoth(){
        state=new PeacefulState(this);
    }
    public void timePasses(){
        if(state.getClass().equals((PeacefulState.class))){
            changeStateTo(new AngryState(this));
        }else {
            changeStateTo(new PeacefulState(this));
        }
    }
    private void changeStateTo(State newState){
        this.state=newState;
        this.state.onEnterState();
    }

    @Override
    public String toString() {
        return "The mammoth";
    }
    public void observe(){
        this.state.observe();
    }
}

核心就是Mammoth这个类里面实现了逻辑切换了两个类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值