explain state pattern in design patterns
- User
explain state pattern in design patterns
- Assistant
- User
explain state design pattern with an example real life scenarion code in c++
- Assistant
explain state pattern in design patterns
explain state design pattern with an example real life scenarion code in c++
The State Pattern is a behavioral design pattern used to allow an object to alter its behavior when its internal state changes. This pattern is particularly useful for managing states that may have distinct behaviors and can simplify complex state management logic within an object.
Context: This is the class that holds the state and delegates behavior to its current state object. The context interacts with the state interface but doesn't know the details of the concrete states.
State Interface: This interface defines the methods that are applicable to the various states of the context. Each state will implement this interface.
Concrete States: These are the classes that implement the state interface. Each concrete state represents a specific state of the context and defines its behaviors accordingly.
Initialization: The context starts in a specific state.
State Transition: The context can change its state during execution, often in response to some events or method calls. When the state changes, the context performs behavior specific to the new state.
Behavior Delegation: Instead of implementing all behaviors directly in the context, it delegates the behavior calls to the current state object. The state object decides what action to take based on its own logic.
Consider a simple traffic light system. The traffic light has three states: Green, Yellow, and Red. Each state will define how long the light should stay in that state, and what the next state should be.
class TrafficLightState:
def change(self):
pass
class GreenLight(TrafficLightState):
def change(self):
print("Green light -> next: Yellow")
return YellowLight()
class YellowLight(TrafficLightState):
def change(self):
print("Yellow light -> next: Red")
return RedLight()
class RedLight(TrafficLightState):
def change(self):
print("Red light -> next: Green")
return GreenLight()
class TrafficLight:
def __init__(self):
self.state = GreenLight() # Initial state
def change(self):
self.state = self.state.change()
if __name__ == "__main__":
traffic_light = TrafficLight()
for _ in range(6): # Cycle through the lights multiple times
traffic_light.change()
Using the State Pattern helps to keep the control flow of different states organized and focuses on one responsibility per class, promoting better practices in software design and implementation.
The State Design Pattern is useful in scenarios where an object can exist in multiple states, and the behavior of the object changes based on its current state. A classic example of this could be a Vending Machine that changes its behavior based on the state of the machine.
We'll build a simple vending machine that can be in three states: No Coin, Has Coin, and Dispensing Item.
#include <iostream>
#include <memory>
// Forward declaration of VendingMachine to use in State interface
class VendingMachine;
// State interface
class State {
public:
virtual ~State() {}
virtual void insertCoin() = 0;
virtual void selectItem() = 0;
virtual void dispenseItem() = 0;
};
// Context class
class VendingMachine {
private:
std::unique_ptr<State> state;
public:
VendingMachine();
void setState(std::unique_ptr<State> newState) {
state = std::move(newState);
}
void insertCoin() {
state->insertCoin();
}
void selectItem() {
state->selectItem();
}
void dispenseItem() {
state->dispenseItem();
}
};
// Concrete state classes
class NoCoinState : public State {
public:
void insertCoin() override {
std::cout << "Coin inserted.\n";
std::cout << "Transitioning to HasCoinState.\n";
// Transition to HasCoinState
// Note: Context's setState can be called here
}
void selectItem() override {
std::cout << "You need to insert a coin first.\n";
}
void dispenseItem() override {
std::cout << "No item dispensed. Please insert a coin first.\n";
}
};
class HasCoinState : public State {
private:
VendingMachine* machine;
public:
HasCoinState(VendingMachine* machine) : machine(machine) {}
void insertCoin() override {
std::cout << "Coin already inserted. Select an item.\n";
}
void selectItem() override {
std::cout << "Item selected.\n";
std::cout << "Transitioning to DispensingItemState.\n";
// Transition to DispensingItemState
machine->setState(std::make_unique<DispensingItemState>(machine));
}
void dispenseItem() override {
std::cout << "You need to select an item first.\n";
}
};
class DispensingItemState : public State {
public:
void insertCoin() override {
std::cout << "Please wait, dispensing item!\n";
}
void selectItem() override {
std::cout << "Dispensing in progress. Please wait.\n";
}
void dispenseItem() override {
std::cout << "Item dispensed. Enjoy!\n";
std::cout << "Transitioning to NoCoinState.\n";
// Transition to NoCoinState after dispensing
// Note: Context's setState can be called here
}
};
// Implementation of VendingMachine constructor to set initial state
VendingMachine::VendingMachine() {
state = std::make_unique<NoCoinState>();
}
int main() {
VendingMachine machine;
machine.selectItem(); // Expect message about inserting a coin first
machine.insertCoin(); // Insert coin
machine.state->selectItem(); // Select an item
machine.state->dispenseItem(); // Dispense the item
return 0;
}
Context Class (VendingMachine): Holds the current state and delegates method calls to that state. It allows state transitions.
State Interface (State): Defines methods for operations that can be performed in different states.
Concrete States:
VendingMachine starts in the NoCoinState.HasCoinState, allowing the user to select an item.DispensingItemState, where the item is dispensed, and finally returns to NoCoinState.This example demonstrates how the State Pattern separates concerns and encapsulates state-specific behavior, making the code easier to maintain and extend in future scenarios.
Not yet included in a published release.