State
Alter an object's behavior when its state changes.
The State pattern provides state-specific logic to a limited set of objects in which each object represents a particular state.
In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.
EX:
class AlertStateContext {
private currentState;
public AlertStateContext()
{
currentState = new Vibration();
}
public setState(state)
{
currentState = state;
}
public alert()
{
currentState.alert(this);
}
}
class Vibration {
public alert(AlertStateContext ctx)
{
System.out.println("vibration...");
}
}
class Silent {
public void alert(AlertStateContext ctx)
{
System.out.println("silent...");
}
}
function run() {
AlertStateContext stateContext = new AlertStateContext();
stateContext.alert(); // vibration...
stateContext.alert(); // vibration...
stateContext.setState(new Silent());
stateContext.alert(); // silent...
stateContext.alert(); // silent...
stateContext.alert(); // silent...
}
run();
Last updated
Was this helpful?