Technology Sharing

State Pattern

2024-07-11

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

State Pattern

definition

Also known as State Machine Pattern
By defining different state classes to encapsulate behaviors related to specific states and transferring the state judgment logic to a series of classes representing different states, complex judgment logic can be simplified.

  • The State pattern separates state and behavior, enabling an object to change its behavior when its internal state changes.
  • Each state corresponds to a subclass, so the state conversion logic is distributed to the state subclasses, reducing mutual dependence.
  • Clients usually do not interact with state objects directly, but interact with state objects through the environment class (Context).

Applicable scene

  1. An object's behavior depends on its state, and it must change its behavior at runtime based on that state.
  2. An operation contains a large multi-branch structure, and these branches depend on the state of the object.

Standard Examples

insert image description here

In the state mode structure diagram, the following roles are usually included:

  • Context (environment class): Also known as the context class, it is an object with multiple states. An instance of the abstract state class State is maintained in the environment class, which defines the current state.
  • State (abstract state class): used to define an interface to encapsulate behaviors related to a specific state of an environment class. Methods corresponding to various states are declared in the abstract state class and implemented in subclasses.
  • ConcreteState (concrete state class): It is a subclass of the abstract state class, each subclass implements a behavior related to a state of the environment class.

IState

public interface IState {
    void handle();
}