// Context class class TrafficLight { public: virtual void ChangeState(TrafficLightState* state) { current_state_ = state; } void Request() { current_state_->Handle(); } private: TrafficLightState* current_state_; }; // State classes class TrafficLightState { public: virtual void Handle() = 0; }; class GreenLight : public TrafficLightState { public: void Handle() override { // Turn the light on for green } }; class YellowLight : public TrafficLightState { public: void Handle() override { // Turn the light on for yellow } }; class RedLight : public TrafficLightState { public: void Handle() override { // Turn the light on for red } };
// Context class class Order { public: Order() { current_state_ = new PendingState(); } ~Order() { delete current_state_; } void ChangeToConfirmed() { delete current_state_; current_state_ = new ConfirmedState(); } void ChangeToShipped() { delete current_state_; current_state_ = new ShippedState(); } void DisplayStatus() { current_state_->DisplayStatus(); } private: OrderState* current_state_; }; // State classes class OrderState { public: virtual void DisplayStatus() = 0; }; class PendingState : public OrderState { public: void DisplayStatus() override { std::cout << "Your order is pending..." << std::endl; } }; class ConfirmedState : public OrderState { public: void DisplayStatus() override { std::cout << "Your order has been confirmed!" << std::endl; } }; class ShippedState : public OrderState { public: void DisplayStatus() override { std::cout << "Your order has been shipped!" << std::endl; } };In C++, the State pattern can be found in the Boost library. There is a Boost.Statechart package that provides a framework for building state machines. This package includes classes for state machines, events, and transition actions.