State Pattern
State Pattern
In State pattern a class behavior changes based on its state. This type of design
pattern comes under behavior pattern.
In State pattern, we create objects which represent various states and a context
object whose behavior varies as its state object changes.
Implementation
We are going to create a State interface defining an action and concrete state
classes implementing the State interface. Context is a class which carries a State.
StatePatternDemo, our demo class, will use Context and state objects to
demonstrate change in Context behavior based on type of state it is in.
Step 1
Create an interface.
State.java
https://www.tutorialspoint.com/design_pattern/state_pattern.htm 1/4
15/01/24, 11:51 Design Patterns - State Pattern
Step 2
Create concrete classes implementing the same interface.
StartState.java
StopState.java
Step 3
Create Context Class.
https://www.tutorialspoint.com/design_pattern/state_pattern.htm 2/4
15/01/24, 11:51 Design Patterns - State Pattern
Context.java
public Context(){
state = null;
}
Step 4
Use the Context to see change in behaviour when State changes.
StatePatternDemo.java
System.out.println(context.getState().toString());
System.out.println(context.getState().toString());
}
}
Step 5
https://www.tutorialspoint.com/design_pattern/state_pattern.htm 3/4
15/01/24, 11:51 Design Patterns - State Pattern
https://www.tutorialspoint.com/design_pattern/state_pattern.htm 4/4