C++ State Pattern Example

In this article, we will learn how to use and implement the State Pattern in C++ with an example.

State is a behavioral design pattern that lets an object alter its behavior when its internal state changes. It appears as if the object changed its class.

C++ State Pattern Example

#include <iostream>

/*
 * State
 * defines an interface for encapsulating the behavior associated
 * with a particular state of the Context
 */
class State
{
public:
    virtual ~State() {
        /* ... */
    }
    virtual void handle() = 0;
    // ...
};

/*
 * Concrete States
 * each subclass implements a behavior associated with a state
 * of the Context
 */
class ConcreteStateA : public State
{
public:
    ~ConcreteStateA() {
        /* ... */
    }

    void handle()
    {
        std::cout << "State A handled." << std::endl;
    }
    // ...
};

class ConcreteStateB : public State
{
public:
    ~ConcreteStateB() {
        /* ... */
    }

    void handle()
    {
        std::cout << "State B handled." << std::endl;
    }
    // ...
};

/*
 * Context
 * defines the interface of interest to clients
 */
class Context
{
public:
    Context() : state() {
        /* ... */
    }

    ~Context()
    {
        delete state;
    }

    void setState( State* const s )
    {
        if ( state )
        {
            delete state;
        }
        state = s;
    }

    void request()
    {
        state->handle();
    }

private:
    State *state;
};


int main()
{
    Context *context = new Context();

    context->setState( new ConcreteStateA() );
    context->request();

    context->setState( new ConcreteStateB() );
    context->request();

    delete context;
    return 0;
}

Output

State A handled.
State B handled.

When to use?

  • when an object's behavior depends on its state, and it must change its behavior at run-time depending on that state
  • operations have large, multipart conditional statements that depend on the object's state

Comments