State | Cheat Sheet

Behavioral Pattern — Design Patterns Series

Itchimonji
CP Massive Programming
3 min readAug 9, 2021

--

Nowadays, a State can be found in a lot of application architectures: Web page state, database state (set of stored data), or stateful sets like MQTT — shortly explained, the entire content of its memory, e.g. all its variables, objects allocated, or open network sockets.

The pattern describes how changing the internal state affects the external behaviour, e.g. class changes.

Real-life examples

  • Screen states of the mobile phone: Lock Screen, Battery Low Screen, Unlocked Screen, …
  • Traffic lights in road traffic
  • Video games: Play, Pause, Load, Connect, …
  • Using the remote control to achieve various states on TV: on, off, mute, colour ratio, …
  • Ticket vending machine
  • Application Controller in Web pages: 1 controller handles different views as responses

Meaning

  • Adaptation of the behaviour of an object in case of an internal change of state (effect like class change)

Applicability (suitable if …)

  • The behaviour of an object depends on its state and its behaviours must be changed at runtime from this state
  • Operations depend on the state of the object (e.g. switch statement)

Assets and Drawbacks

  • Inventory of state-specific behaviours + distributes them to different states (state-specific code is in state subclass and thus allows easy extension)
  • Changes of state are clearly highlighted
  • State objects can be shared

Example

A good programmable example would be to change the mobile phone display from a locked view to an unlocked view.

Therefore, you need to start with the definition of the various screen states in an interface. A display can be locked, unlocked, and show a low energy icon when the battery is running low.

With an abstract class you can equip the interface to throw a runtime error if the method in the subclass is not implemented:

Now you can define the concrete classes for the different states:

At last, you need a mobile phone class that can switch between different states:

Conclusion

Design Patterns are an important resource and base knowledge for every developer — they are very helpful for solving programmatic problems, help with consistent communication with other developers about system design, and serve as a significant introduction into object composition (besides inheritance) and dependency inversion.

Behavioral Patterns deal with algorithms and assignment of responsibilities to objects. Furthermore, they describe mutual communication patterns and grasp complex program sequences. They are therefore very well suited for use in areas where complicated code needs to be made readable and maintainable. Extensions are, in consequence, very good and quickly implementable.

--

--

Itchimonji
CP Massive Programming

Freelancer | Site Reliability Engineer (DevOps) / Kubernetes (CKAD) | Full Stack Software Engineer | https://patrick-eichler.com/links