Friday, 22 April 2016

State Design Pattern

State design pattern

It is very similar to Strategy design pattern. But it has basic differences.
Strategy interface of Strategy design pattern ~= State interface of State design pattern

Differences of State design pattern from Strategy design pattern.
1.     The algorithmic behavioral changes are managed by the “State”s itself. In case of Strategy design pattern, the client controls it.
2.     The States contain reference of the Context.  They use it to change the next behavior of the Context. Strategy classes don’t have any such reference.
3.     In case of Strategy pattern, it's client, which provides different strategy to Context, on State pattern, state transition is managed by Context or State itself.
4.     Order of State transition is well defined in State pattern, there is no such requirement for Strategy pattern.
5.      Once good example is that in sorting, using the Comparator is like using Strategy design pattern and using Comparable is like using State design pattern


State
Play Button
Standby
Start playing music from start
MP3 Playing
Stop music, switch state to “MP3 Paused”.
MP3 Paused
Start music, switch state to “MP3 Playing”.
In case of the play button of a tape-recorder, when it’s in standby mode, it should start playing music from start. When tape-recorder is playing, the same switch should pause the music if pressed. When tape-recorder is paused, the same switch, if pressed, should start playing music from the pt. its paused.

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

public class StandbyState implements State {
      @Override
      public void pressPlay(Context context) {
            System.out.println("Playing music from start");
            context.setState(new PlayingState());
      }

}

public class PausedState implements State {
      @Override
      public void pressPlay(Context context) {
            System.out.println("Pausing music");
            context.setState(new PlayingState());
      }

}

public class PlayingState implements State {

      @Override
      public void pressPlay(Context context) {
            System.out.println("Playing music from paused point");
            context.setState(new PausedState());
      }

}

public class Context {
     
      private State state;

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

      public void pushPlayButton() {
            state.pressPlay(this);
      }

}

public class MainClass {   
      public static void main(String[] args) {
            Context context = new Context(new StandbyState());
            context.pushPlayButton();
            context.pushPlayButton();
            context.pushPlayButton();
            context.pushPlayButton();
      }

}


Code link : https://github.com/sksumit1/DesignPatterns

No comments:

Post a Comment