Friday, May 27, 2016

Design Pattern - Sate Design Pattern tutorial example java

What is State Design Pattern?

The sate design pattern is a behavioral  object design pattern.The idea behind the state patterns is to change object behavior depending on its state.State Pattern allows objects to behave differently depending on internal state that is Context.The context can have a number of internal states whenever the request method is called on the Context,the message is delegated to the State to handle.

For Example:
The control panel of a simple media player could be used as an example.Can have many states such as Play,Pause,Stop and Restart etc.

Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */
interface State
{
  public void pressPlay(MusicPlayerContextInterface context);
}

class StandbyState implements State
{

@Override
public void pressPlay(MusicPlayerContextInterface context)
{
 context.setState(new PlayingState());
}

}

class PlayingState implements State
{

@Override
public void pressPlay(MusicPlayerContextInterface context) {
// TODO Auto-generated method stub
context.setState(new StandbyState());
}

}

interface MusicPlayerContextInterface
{
  // public State state;
  public void requestPlay();
  public void setState(State state);
  public State getState();
}


class MusicPlayerContext implements MusicPlayerContextInterface
{
   State state;

   public MusicPlayerContext(State state)
   {
  this.state=state;
   }
 
@Override
public void requestPlay() {
// TODO Auto-generated method stub
state.pressPlay(this);
}

@Override
public void setState(State state) {
// TODO Auto-generated method stub
this.state=state;
}

@Override
public State getState() {
// TODO Auto-generated method stub
return state;
}

}

public class StatePatternTest {

/**
* @param args
*/
public static void main(String[] args)
{

MusicPlayerContext musicPalyer=new MusicPlayerContext(new StandbyState());
musicPalyer.requestPlay();
musicPalyer.setState(new PlayingState());
musicPalyer.requestPlay();
}


}

Advantages of State Design Pattern:

  • State patterns provides a clear state representation of an Object.
  • It allows a clear way for an object change its type at runtime.


No comments: