State Design Pattern
Saji Kuttan
Senior Software Engineer @HCL TECH | Ex-Infoscion | Building Secure and Scalable Software's | Full Stack Developer
The State Design Pattern is a behavioral design pattern that allows an object to change its behavior when its internal state changes. It helps manage state transitions cleanly by encapsulating state-specific behavior into separate state classes.
Traffic Light Example with State Design Pattern
Imagine a traffic light system where the light can be in one of three states: Red, Green, or Yellow. Depending on its current state, the light behaves differently. This is a perfect scenario for applying the State Design Pattern, as each light state has distinct behaviors and transitions.
Key Components of the State Pattern:
Example:
Let's break it down in code:
Step 1: Define the LightState interface .
// The State interface
public interface LightState {
void switchLight(TrafficLight trafficLight);
}
Step 2: Create Concrete States for Red, Green, and Yellow lights.
// RedLight State
public class RedLight implements LightState {
@Override
public void switchLight(TrafficLight trafficLight) {
System.out.println("Red Light - Stop!");
trafficLight.setState(new GreenLight()); // Transition to Green after Red
}
}
// GreenLight State
public class GreenLight implements LightState {
@Override
public void switchLight(TrafficLight trafficLight) {
System.out.println("Green Light - Go!");
trafficLight.setState(new YellowLight()); // Transition to Yellow after Green
}
}
// YellowLight State
public class YellowLight implements LightState {
@Override
public void switchLight(TrafficLight trafficLight) {
System.out.println("Yellow Light - Slow Down!");
trafficLight.setState(new RedLight()); // Transition to Red after Yellow
}
}
Step 3: Define the TrafficLight context class
领英推荐
// The Context Class
public class TrafficLight {
private LightState currentState;
public TrafficLight() {
// Start with Red Light
this.currentState = new RedLight();
}
public void setState(LightState state) {
this.currentState = state;
}
public void changeLight() {
currentState.switchLight(this);
}
}
Step 4: Demonstrate the Traffic Light State Transitions
public class Main {
public static void main(String[] args) {
TrafficLight trafficLight = new TrafficLight();
// Simulate the traffic light changing states
for (int i = 0; i < 6; i++) {
trafficLight.changeLight();
}
}
}
Output:-
Red Light - Stop!
Green Light - Go!
Yellow Light - Slow Down!
Red Light - Stop!
Green Light - Go!
Yellow Light - Slow Down!
Explanation:
Advantages:
Conclusion:
The State Design Pattern helps in organizing code that involves transitions between different states, like a traffic light system. Each light (Red, Green, Yellow) is a state, and the pattern handles smooth transitions between them while maintaining clean, manageable code.
#SoftwareDesign #StatefulPattern #Architecture #DesignPatterns #Developers #ProgrammingTips