State
Last updated
Last updated
State is a behavioral design pattern that lets an object alter its behavior when its internal state changes. It appears as if the object changed its class.
The State design pattern is a behavioral design pattern that allows an object to alter its behavior when its internal state changes.
This pattern is particularly useful when an object's behavior depends on its state, and the behavior needs to change dynamically as the state changes.
In JavaScript, you can implement the State pattern using objects and closures to encapsulate the states and their respective behaviors.
Sure, here's a simple example of the State design pattern in JavaScript:
In this example:
The TrafficLight
class represents the context of the state machine.
It maintains a reference to the current state and provides methods to change the state and request actions from the current state.
The TrafficLightState
class is an interface for concrete state classes to implement.
Concrete state classes (RedLight
, YellowLight
, GreenLight
) represent different states of the traffic light.
Each concrete state class provides its implementation of the action()
method.
The example demonstrates how the traffic light changes its state and performs actions accordingly.
This example illustrates the State design pattern where the behavior of an object changes based on its internal state.