knowledge/technology/dev/programming/patterns/behavioral/State Patterns.md

82 lines
3.6 KiB
Markdown
Raw Normal View History

2023-12-04 10:02:23 +00:00
---
obj: concept
---
# State Pattern
## **Description:**
The State Pattern is a behavioral design pattern that allows an object to alter its behavior when its internal state changes. The object appears to change its class, making it useful for modeling objects with complex state-dependent behaviors. It encapsulates the states as separate classes and allows the context (the object whose state is changing) to delegate state-specific behavior to these state classes.
**How it's Used:**
1. **State Interface/Abstract Class**: Define a state interface or abstract class that declares methods for the various actions or behaviors that can change based on the state.
2. **Concrete States**: Create concrete state classes that implement the state interface/abstract class. Each concrete state class represents a specific state and provides its own implementation of the state-specific behaviors.
3. **Context**: Define a context class that maintains a reference to the current state object. The context class delegates state-specific behavior to the current state object.
4. **State Transition**: Implement methods in the context class for transitioning between states. These methods change the current state to a different state as needed.
## **Example:**
Let's create an example of the State Pattern in [Python](../../languages/Python.md) to model the behavior of a traffic light with three states: "Green," "Yellow," and "Red."
```python
from abc import ABC, abstractmethod
# Step 1: State Interface
class TrafficLightState(ABC):
@abstractmethod
def display(self):
pass
@abstractmethod
def transition(self, traffic_light):
pass
# Step 2: Concrete States
class GreenLightState(TrafficLightState):
def display(self):
return "Green"
def transition(self, traffic_light):
traffic_light.set_state(YellowLightState())
class YellowLightState(TrafficLightState):
def display(self):
return "Yellow"
def transition(self, traffic_light):
traffic_light.set_state(RedLightState())
class RedLightState(TrafficLightState):
def display(self):
return "Red"
def transition(self, traffic_light):
traffic_light.set_state(GreenLightState())
# Step 3: Context (TrafficLight)
class TrafficLight:
def __init__(self):
self.state = GreenLightState()
def set_state(self, state):
self.state = state
def change_state(self):
self.state.transition(self)
def display_state(self):
return self.state.display()
# Step 4: Client Code
def main():
traffic_light = TrafficLight()
for _ in range(5):
print(f"Current Light: {traffic_light.display_state()}")
traffic_light.change_state()
if __name__ == "__main__":
main()
```
In this [Python](../../languages/Python.md) example, we define a `TrafficLightState` interface (Step 1) with `display` and `transition` methods. We create three concrete state classes (`GreenLightState`, `YellowLightState`, and `RedLightState`) (Step 2) that implement this interface, representing the states of the traffic light.
The `TrafficLight` class (Step 3) is the context class that maintains a reference to the current state and delegates state-specific behavior to that state. The `change_state` method transitions to the next state in the sequence.
In the `main` function (Step 4), we create a traffic light, display its state, and change the state to simulate the behavior of a traffic light changing from green to yellow to red and back to green. The State Pattern allows us to manage the traffic light's behavior in a flexible and maintainable way.