BehavioralC++verifiedVerified

State Pattern in C++

Allows an object to alter its behavior when its internal state changes, appearing as if the object has changed its class.

How to Implement the State Pattern in C++

1Step 1: Define the State interface

class State {
public:
    virtual ~State() = default;
    virtual std::string name() const = 0;
    virtual std::unique_ptr<State> next() const = 0;
    virtual std::string action() const = 0;
};

2Step 2: Concrete states

class GreenState : public State {
public:
    std::string name() const override { return "GREEN"; }
    std::unique_ptr<State> next() const override;
    std::string action() const override { return "Cars may proceed"; }
};

class YellowState : public State {
public:
    std::string name() const override { return "YELLOW"; }
    std::unique_ptr<State> next() const override;
    std::string action() const override { return "Cars should slow down"; }
};

class RedState : public State {
public:
    std::string name() const override { return "RED"; }
    std::unique_ptr<State> next() const override {
        return std::make_unique<GreenState>();
    }
    std::string action() const override { return "Cars must stop"; }
};

std::unique_ptr<State> GreenState::next() const {
    return std::make_unique<YellowState>();
}
std::unique_ptr<State> YellowState::next() const {
    return std::make_unique<RedState>();
}

3Step 3: Context that delegates to the current state

class TrafficLight {
    std::unique_ptr<State> state_;
public:
    TrafficLight() : state_(std::make_unique<RedState>()) {}

    void transition() { state_ = state_->next(); }

    void display() const {
        std::cout << "[" << state_->name() << "] " << state_->action() << "\n";
    }
};

int main() {
    TrafficLight light;
    for (int i = 0; i < 6; ++i) {
        light.display();
        light.transition();
    }
}

State Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

State Pattern in the Real World

Think of a traffic light. The light itself (context) doesn't change its wiring, but its active state—red, yellow, or green—completely determines what drivers should do. Each color has its own rules, and the light transitions through states on a timer. Adding a flashing-yellow state only requires defining that state's rules, not rewiring the entire light.