状态模式 (State Pattern)

状态模式允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。

复制代码
public class Main {
    
    public static void main(String[] args) {
        Context context = new Context();
        
        StartState startState = new StartState();
        startState.doAction(context);
   
        System.out.println(context.getState().toString());
   
        StopState stopState = new StopState();
        stopState.doAction(context);
   
        System.out.println(context.getState().toString());
    }
}

class Context {
    
    private State state = null;
  
    public State getState() {
        return state;
    }
    public void setState(State state) {
        this.state = state;     
    }
}

interface State {
    public void doAction(Context context);
}

class StartState implements State {
    
    public void doAction(Context context) {
        System.out.println("Player is in start state");
        context.setState(this); 
    }
  
    public String toString() {
        return "Start State";
    }
}
class StopState implements State {
    
    public void doAction(Context context) {
        System.out.println("Player is in stop state");
        context.setState(this); 
    }
  
    public String toString() {
        return "Stop State";
    }
}
复制代码

 

posted @   HanselHuang  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示