A guide to software design patterns

Behavioral Design Pattern: State

Peterson C
The Startup
4 min readFeb 13, 2020

--

Photo by Fabian Grohs on Unsplash

The state pattern is one of the eleven current behavioral software design patterns. It allows an object to change its behavior when its internal state changes. This pattern makes it easy to change an object’s behavior without having to check the current of the object with a conditional statement, which makes a codebase flexible, testable and maintainable.

Pattern Ideal Usage

When should this pattern be used? Let’s say you’re in charge of designing a system that changes the input of an audio device. There are multiple inputs we can change to but the switch happens in sequential order ( e.g. Bluetooth, Optical, Coaxial, RCA and USB). One input will always be selected.

This scenario would be a good use of the state pattern. It doesn’t matter what’s being done underneath the hood of the audio device, we just care that it changes from one input (state) to the next when we hit the switch button.

Implementation

What would that look like in code? Each state would perform some work to transition to the new state — i.e. to…

--

--

Peterson C
The Startup

Husband, father, engineer, musician, and writer by luck. I write mostly about whatever comes to mind. Follow me on this crazy writing journey if you dare.