美文网首页
状态(State)模式

状态(State)模式

作者: 莫库施勒 | 来源:发表于2019-08-02 19:27 被阅读0次
    public interface State {
       public void doAction(Context context);
    }
    
    public 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";
       }
    }
    
    public 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";
       }
    }
    
    public class Context {
       private State state;
     
       public Context(){
          state = null;
       }
     
       public void setState(State state){
          this.state = state;     
       }
     
       public State getState(){
          return state;
       }
    }
    
    public class StatePatternDemo {
       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());
       }
    }
    

    相关文章

      网友评论

          本文标题:状态(State)模式

          本文链接:https://www.haomeiwen.com/subject/jwerdctx.html