The State Pattern

Learn about the State pattern with the help of coding implementation.

Overview

The State pattern is structurally similar to the Strategy pattern, but its intent and purpose are very different. The goal of the State pattern is to represent state transition systems: systems where an object’s behavior is constrained by the state it’s in, and there are narrowly defined transitions to other states.

To make this work, we need a manager or context class that provides an interface for switching states. Internally, this class contains a pointer to the current state. Each state knows what other states it is allowed to be in and will transition to those states depending on the actions invoked upon it.

Here’s how it looks in UML:

Press + to interact
The UML diagram of the State pattern
The UML diagram of the State pattern

The State pattern decomposes the problem into two types of classes: the Core class and multiple State classes. The Core class maintains the current state, and forwards actions to a current state object. The State objects are typically hidden from any other objects that are calling the Core object; it acts like a black box that happens to perform state management internally.

A State example

One of the most compelling state-specific processing examples is parsing text. When we write a regular expression, we’re detailing a series of alternative state changes used to match a pattern against a sample piece of text. At a higher level, parsing the text of a programming language or a markup language is also highly stateful work. Markup languages like XML, HTML, YAML, TOML, or even reStructuredText and Markdown all have stateful rules for what is allowed next and what is not allowed next.

We’ll look at a relatively simple language that crops up when solving Internet of Things (IoT) problems. The data stream from a GPS receiver is an interesting problem. Parsing statements in this language is an example of the State design pattern. The language is the NMEA 0183 language from the National Marine Electronics Association.

The output from a GPS antenna is a stream of bytes that form a sequence of sentences. Each sentence starts with $, includes printable characters in the ASCII encoding, and ends with a carriage return and a newline character. A GPS device’s output includes a number of different kinds of sentences, including the following:

  • GPRMC — recommended minimum data
  • GPGGA — global position
  • GPGLL — latitude and longitude
  • GPGSV — satellites in view
  • GPGSA — active satellites

There are many, many more messages available, and they come out of the antenna device at a pace ...