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.
We’ve been looking for this information for a very long time.
ReplyDeleteInteresting post. I Have Been wondering about this issue, so thanks for posting.
ReplyDeleteI do trust all of the concepts you have presented to your post.
ReplyDeleteI like the valuable information you provide in your articles.
ReplyDeleteThis is really interesting, You’re a very skilled blogger.
ReplyDeleteThanks a lot for sharing this with all folks you really realize what you’re talking approximately! Bookmarked.
ReplyDeleteHelpful and interesting too. Thank you.
ReplyDelete