This is the 26th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
An overview of the
A State Pattern is one that allows the behavior of an object to change when its internal State changes so that the class of the object appears to have been modified. Therefore, it is also called the Objects for States mode, which is an object behavior mode.
The state mode is mainly used to solve two problems in the system, one is the transformation of the state of complex objects, the other is the encapsulation of the behavior of objects in different states. The state pattern is used when an object in the system has multiple states that can be transferred between them, and the object behaves differently in each state.
The state mode extracts the state of an object from the object and encapsulates it into a special state class, so that the state of the object can be flexibly changed. For the client, there is no need to care about the object state transition and the current state of the object, regardless of the state of the object, the client can be consistent processing.
structure
- Context: Also known as a Context class, it is an object with multiple states.
- State (Abstract State class) : Typically an interface or abstract class that defines the behavior of a particular State of the environment class.
- ConcreteState: Each ConcreteState class implements the behavior of a specific state of the environment class.
advantages
- It decouples the behavior and state of the object, reduces the complexity of the system, improves the maintainability of the system, and conforms to the principle of single responsibility.
- Adding the behavior of the object does not need to modify the client code, in accordance with the open closed principle.
- You can reduce the number of objects in the system by having multiple environment objects share a state object.
- The transformation of the object state is placed in the internal, the client does not have to know how to realize the state and behavior of the internal class switch, in accordance with Demeter’s law.
disadvantages
- Too many states cause class inflation, which is unfavorable for maintenance.
- The number of classes and objects in the system increases, which increases the operating cost of the system.
- The structure and implementation of state pattern are complicated, and it will lead to confusion of program structure and code if used improperly.
- When adding a new state class, we need to modify the source code responsible for state transition, which does not comply with the open and close principle.
Application scenarios
- Behavior changes as states change.
- Consider using state mode when a large number of conditional and branch statements are required in a program.
Applications in the JDK
In the JDK, java.util.Iterator uses state mode.