'JAVA/JAVA Design pattern'에 해당되는 글 1건

현재 상황에 따라 같은 일에 대해 다르게 반응을 합니다. 배가 고플 때 밥을 먹으면 배가 부릅니다. 하지만 배가 부를 때 밥을 또 먹으면 배터질 것 같아 화가 납니다. 같은 행동인 "밥을 먹는 것"에 대해 현재 상태가 "배부름"인지 "배고픔"인지에 따라 행동이 달라지는 것입니다.


interface State {

  public void doAction(Context context);

}// w w w  .  ja  va  2  s. co  m


class StartState implements State {

  public void doAction(Context context) {

    System.out.println("In start state"+ this);

    context.setState(this);

  }


  public String toString1() {

    return "Start dStat111e";

  }

  

}


class StopState implements State {


  public void doAction(Context context) {

    System.out.println("In stop state");

    context.setState(this);

  }


  public String toString() {

    return "Stop State";

  }

}


class PlayState implements State {

  public void doAction(Context context) {

    System.out.println("In play state");

    context.setState(this);  

  }

  public String toString() {

    return "Play State";

  }

}


class Context {

  private State state;


  public Context() {

    state = null;

  }


  public void setState(State state) {

    this.state = state;

  }


  public State getState() {

    return state;

  }

}


public class test {

  public static void main(String[] args) {

    Context context = new Context();


    StartState startState = new StartState();

    startState.doAction(context);


    System.out.println(context.getState().toString());


    PlayState playState = new PlayState();

    playState.doAction(context);

    

    StopState stopState = new StopState();

    stopState.doAction(context);


    System.out.println(context.getState().toString());

  }

}

블로그 이미지

왕왕왕왕

,