State: Introduction

Get a brief introduction to the State design pattern.

The State design pattern allows developers to change the behavior of an object depending on what state the object is in. The public interface of the object, however, remains the same.

We can think of it as being analogous to a smartphone. When the phone is in a locked state, pressing the “Home” button brings up a prompt for the unlock PIN. However, if the phone is already unlocked, pressing the same button takes us to the home screen. It’s the same button but it behaves differently if our device is in a different state. The same thing can be done in the code.

Summarized concepts of the State design pattern

The State design pattern can be summarized as follows:

  • There’s a Context object, which contains the State interface.
  • The State interface has multiple implementations, each with its own behavior.
  • The role of the Context object is to trigger specific public methods in the current State implementation and to allow the State implementation to be changed.
  • State implementations are never manipulated directly by an external client. Only the Context object is called directly by outer code.
  • However, the outer code can instruct the Context object to change the concrete implementation of the State object inside itself.

Get hands-on with 1200+ tech skills courses.