State Pattern

State is a behavioral design pattern, in which a class behavior changes based on its state. In State pattern there are objects which represent various states and a context object whose behavior varies as its state object changes.

In the example below there is a State interface defining an action and concrete classes implementing the State interface. Context is a class which carries a State. StatePatternDemo will use Context and state objects to demonstrate change in Context behavior based on type of state it is in.

State Pattern UML Diagram

Step 1 : Create an interface

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

Step 2 : Create concrete classes implementing the same interface

public class StartState implements State {
@Override
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 {
@Override
public void doAction(Context context) {
System.out.println("Player is in stop state");
context.setState(this);
}

public String toString() {
return "Stop State";
}
}

Step 3 : Create Context class

public class Context {
private State state;

public State getState() {
return state;
}

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

Step4 : Use the Context to see changes in behavior when State changes

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());

StopState stopState = new StopState();
stopState.doAction(context);
System.out.println(context.getState());
}
}

The output will be : 

Player is in start state
Start State
Player is in stop state
Stop State

Leave a Reply

Your email address will not be published. Required fields are marked *