Tuesday, January 27, 2015

State Design Pattern

Design Pattern > Behavioral Design Pattern > State Design Pattern

The intent of state design pattern is to allow the object to change it's behaviour when there is change in the state of object.

Key Terms :
State Interface - represents the different states involved


  • Declares method to perform action


Concrete State Class -


  • Has method to perform action


Context - This class maintains the current state and is the core of the state design pattern


  • Client has direct access to this class
  • Create and Maintain the current state
  • Provide interface to perform action through state class


Client -

  • Creates Context class instance
  • Creates State objects
  • Changes state of context


Benefits of State Design Pattern :


  • Puts all behavior associated with a state into one object
  • Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement
  • Allows multiple states to be added to the object whithout changing the context class.


Java Implementation :

In this example Robot is a context whose states are walk and stop. RobotState is an State interface and there are two concreate State classes that implement State interface. Default state of Robot is StopState.
Clinet class is remote which can change the state of context ( Robot )

/**
 *  Context Class
 */
package com.kmingle.state;

public class Robot {

private RobotState roboState;

public Robot(){
roboState = new StopState();
}

public RobotState getRoboState() {
return roboState;
}

public void changeRobotState(RobotState roboState) {
this.roboState = roboState;
}

public void doAction(){
roboState.doAction(this);
}
}


/**
 *  State Interface
 */
package com.kmingle.state;

public interface RobotState {

public void doAction(Robot context);
}


/**
 * Concreate State Class
 */
package com.kmingle.state;

public class StopState implements RobotState {

/* (non-Javadoc)
* @see com.kmingle.state.RobotState#doAction(com.kmingle.state.Robot)
*/
@Override
public void doAction(Robot context) {
System.out.println(context.getRoboState().getClass().getSimpleName());
}

}


/**
 * Concreate State Class
 */
package com.kmingle.state;

public class WalkState implements RobotState {

/* (non-Javadoc)
* @see com.kmingle.state.RobotState#doAction(com.kmingle.state.Robot)
*/
@Override
public void doAction(Robot context) {
System.out.println(context.getRoboState().getClass().getSimpleName());
}

}


/**
 * Client Class
 */
package com.kmingle.state;

public class Remote {

public static void main(String[] args) {

Robot robo = new Robot();

robo.doAction();

robo.changeRobotState(new WalkState());

robo.doAction();

}

}

No comments:

Total Pageviews