Definition: In State Pattern, the behavior of a class is changed based on its state.
Features:
1. Encapsulated conversion rules.
2. Enumerate possible states. Before enumerating the state, you need to determine the state type.
3. Put all behaviors related to a certain state into a class, and new states can be easily added. You only need to change the object state to change the object's behavior.
4. Allow state transition logic to be integrated with state objects, rather than a large conditional statement block.
5. Multiple environmental objects can share a state object, thereby reducing the number of objects in the system.
Applications in enterprise and development and common frameworks:
Example:
public class Demo { public static void main(String[] args) { Context context = new Context(); State move = new Move(); move.show(context); State stop = new Stop(); stop.show(context); }}class Context{ private State state; public void setState(State state){ System.out.println("Bless the object state"); this.state = state; }}interface State{ void show(Context context);}class Move implements State{ public void show(Context context) { context.setState(this); System.out.println("Object is in motion"); }}class Stop implements State{ public void show(Context context) { context.setState(this); System.out.println("Object is in motion"); }}State mode is used in situations where there are many object states, such as when completing something, there are states such as unfinished, completed, in progress, and shelved. At this time, you can consider using state mode.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.