Overview
The State Design Pattern allows an object to alter its behavior when its internal state changes. It encapsulates state-specific behavior into separate state objects, promoting the Open/Closed Principle.
Key Characteristics
- Encapsulates state-specific behavior into separate state classes.
- Promotes the Open/Closed Principle by allowing new states to be added without changing existing code.
- Allows behavior to change dynamically at runtime based on the object's state.
Implementation
The following is an example of a State implementation in Java:
// State interface
interface State {
void handleRequest();
}
// Concrete States
class OnState implements State {
@Override
public void handleRequest() {
System.out.println("The device is now ON.");
}
}
class OffState implements State {
@Override
public void handleRequest() {
System.out.println("The device is now OFF.");
}
}
// Context
class Device {
private State currentState;
public Device(State initialState) {
this.currentState = initialState;
}
public void setState(State state) {
this.currentState = state;
}
public void pressButton() {
currentState.handleRequest();
}
}
// Demo
public class StateDemo {
public static void main(String[] args) {
State onState = new OnState();
State offState = new OffState();
Device device = new Device(offState);
device.pressButton(); // OFF -> ON
device.setState(onState);
device.pressButton(); // ON -> OFF
}
}
When to Use
- When an object's behavior depends on its state and it must change behavior at runtime.
- When you want to eliminate conditional statements that depend on the object's state.
Advantages
- Promotes the Open/Closed Principle by allowing new states to be added without modifying existing code.
- Improves maintainability by organizing state-specific behavior into separate classes.
Disadvantages
- Can increase the number of classes in the codebase.
- May introduce complexity if the number of states is large.