DP: State

Command encapsulates a request as an object, allowing parameterization of clients with queues, logs, and undoable operations.

State allows an object to change its behavior when its internal state changes, appearing to change its class.

  • Removes complex state conditionals
  • Improves readability & scalability

C Example

c
#include <stdio.h>

void idleState() { printf("Idle\n"); }
void runState() { printf("Running\n"); }

typedef void (*State)();

int main() {
    State current = idleState;
    current();

    current = runState;
    current();
}

C++ Example

cpp
#include <iostream>
using namespace std;

class State {
public:
    virtual void handle() = 0;
};

class Idle : public State {
public:
    void handle() override { cout << "Idle\n"; }
};

class Running : public State {
public:
    void handle() override { cout << "Running\n"; }
};

class Machine {
    State* state;
public:
    void setState(State* s){ state = s; }
    void run(){ state->handle(); }
};

int main() {
    Machine m;
    Idle idle; Running run;

    m.setState(&idle);
    m.run();

    m.setState(&run);
    m.run();
}