#
State
This tutorial explains to you the design pattern named State (which is a Structural Pattern).
#
State Pattern - theory
State
Design Pattern in Java is used when we want an object to keep a state (or to do something
regarding this change) when an event happened (a method was called).
This state is kept in a context object and can be used in many situations.
The State Pattern is also known as Objects for States.
Take a look at the following UML diagram representing the State design pattern (for my example):
#
State Pattern - example
Here is an example of using the State Design Pattern in Java:
package state.java.pattern.example;
public interface State {
public void doAction(Context context);
public String getLightState();
}
package state.java.pattern.example;
public class Context {
private State state;
public Context(){
state = null;
}
public void setState(State state){
this.state = state;
}
public State getState(){
return state;
}
}
package state.java.pattern.example;
public class TurnLightOn implements State {
private final String lightIs = "ON";
public void doAction(Context context) {
System.out.println("The Light is ON");
context.setState(this);
}
@Override
public String getLightState() {
return lightIs;
}
}
package state.java.pattern.example;
public class TurnLightOff implements State {
private final String lightIs = "OFF";
public void doAction(Context context) {
System.out.println("The Light is OFF");
context.setState(this);
}
@Override
public String getLightState() {
return lightIs;
}
}
package state.java.pattern.example;
public class StateJavaPatternExample {
public static void main(String[] args) {
Context context = new Context();
State turnLightOn = new TurnLightOn();
turnLightOn.doAction(context);
System.out.println("Context = "+context.getState().getLightState());
State turnLightOff = new TurnLightOff();
turnLightOff.doAction(context);
System.out.println("Context = "+context.getState().getLightState());
}
}
When you run this example you will receive the following result: