State Design Pattern

Back To Index

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

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

Advantages

Disadvantages

Back To Index