Allow an object to alter its behavior when its internal state changes.The utility of the state pattern will not be obvious with simple examples that have a very few states and a little conditional logic to switch between states. Such simple state change can be implemented by using state variables and a little conditional logic in each method as shown below.
The object will appear to change its class.
public class SimpleState {
private final String ON_STATE = "on";
private final String OFF_STATE = "off";
// The current state, default is off.
private String currentState = OFF_STATE;
public String redButton() {
if (currentState.equals(ON_STATE)) {
currentState = OFF_STATE;
return "State changed to off";
} else {
return "State was not changed";
}
}
public String greenButton() {
if (currentState.equals(OFF_STATE)) {
currentState = ON_STATE;
return "State changed to on";
} else {
return "State was not changed";
}
}
public static void main(String[] args) {
SimpleState simpleState = new SimpleState();
System.out.println(simpleState.redButton());
System.out.println(simpleState.greenButton());
System.out.println(simpleState.greenButton());
System.out.println(simpleState.redButton());
System.out.println(simpleState.redButton());
System.out.println(simpleState.greenButton());
}
}
- Remove/minimize state-changing conditional logic
- Provide a high-level view of the state changing logic
State Pattern and Strategy Pattern
Although the state pattern looks very much like the strategy pattern, they differ in a few important aspects
- The State Design Pattern can be seen as a self-modifying Strategy Design Pattern.
- A change in state of a class may affect what it does, while a change is strategy of a class only changes how it does the same job.
- In the state pattern, the state of the context object changes over time based on the a few well-defined conditions, while the strategy of a context object is set once, and is not expected to be changed.
No comments:
Post a Comment