State is a behavioural design pattern that allows object to alter its behaviour when its internal state changes. There is a finite number of states which a program can be in, within any unique state, the program behaves differently, and the program can switch from on state to another. Each concrete state class knows which state should come next.
The state object can be pre-created for further use or can be created when needed.
Applicability
You want object to behave differently depending on its current state.
You have complex conditional statements to manage an object’s behaviour based on its state
You anticipate your object will need to support additional states in the future.
Approach
Identify the context by determine the object for which you want to manage different states.
Define the state interface that represents the various states and behaviours the context can perform when in different states.
Create concrete states that each represents a specific state.
Components
Context
It is the client’s interface to the state machine
Maintain an instance of a concrete state that defines the current state.
State (abstract)
Defines an interface for all concrete states, each method in the interface corresponds to a possible behaviour that can be performed at a particular state.
Concrete state
Each concrete state implements the abstract state with encapsulated behaviour associated with a specific state of context.
Example 1
Pre-create state objects and never destroy them
Useful for frequent state changes, save costs of recreating states
Context must keep reference to all states
This example models a simple fan with three states, the fan states can be adjusted.
State interface defines the common actions can be performed on the fan, it defines the contracts for the concrete states.
Concrete state
Each concrete state implements the state interface, providing specific behaviour for actions defined in the interface.
Context
The context Fan maintains a reference to the current state. The context is responsible for transitioning between different states by setting the current state. The states are pre-created for state switching and will never be destroyed.
Client
The client triggers state transitions and observing responses based on the fan’s state.
Example 2
Only when they are needed and destroy them thereafter
States are not known at runtime and context change states frequently
State
The state remains unchanged from the previous example.
Concrete state
The concrete state remains unchanged from the previous example.
Context
The sate is created when needed and is unreferenced and cleaned by the JVM garbage collection mechanism afterwards.
Client
The concrete state remains unchanged from the previous example.
In this example, sate objects are created only when needed and destroyed afterwards. This approach allows you to create and destroy state objects dynamically based on fan’s state.