State

Allow an object to alter its behavior when its internal state changes; the object will appear to change its class. Use when an object's behavior depends on its state and it must change behavior at run-time, or when operations have large multipart conditionals that depend on the object's state.

Examples:

  • A Document object moves through Draft → Moderation → Published states; calling publish() behaves differently in each. Instead of a growing switch statement in a single class, each state (DraftState, ModerationState, PublishedState) is its own class implementing a State interface; the document delegates publish() to the current state object, which may also trigger a state transition.
class TCPState {
public:
  virtual void Open(TCPConnection*) {}
  virtual void Close(TCPConnection*) {}
};
class TCPConnection {
  TCPState* state;
public:
  void ChangeState(TCPState* s) { state = s; }
  void Open()  { state->Open(this); }
  void Close() { state->Close(this); }
};
class TCPEstablished : public TCPState {
  void Close(TCPConnection* c) override { /* transition */ }
};

Synonyms: objects for states