Design Patterns State Pattern

2 min. read

Design Patterns - State Pattern

The state pattern is one of the Behavioural Patterns

Introduction

Just like matter has different states, for example, water has 3 different states, solid, liquid and gas, likewise, in Software Engineering and Computer Science, a class and/or variable can also have a state, depending on its state, the app might function differently.

State management in applications is quite a complex topic.

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

To develop a game or application, you need to think of the state, what can the user do in each state, and more importantly, what can’t a user do in each state.

The state pattern solves the following design challenges:

How does the behaviour change, when its state changes?
How can new behaviours be added without altering the behavior of existing states?

The Unity Animator Controller is a good example of a state Pattern.

Common Mistakes

Multiple Booleans

IsDead IsAlive IsRunning IsShooting IsFollowing

Enums and Switch Statements

Creating an Enum to handle state, and then a Switch statement to handle each state.

What is the problem with this approach?

Each time you add a new state, you need to go update all the switch statements.

Closed
Opening
Idle
Processing
Closing
Closed

State Pattern Components

Context

Maintains an instance of the concrete state as its current state.

Abstract State

Single “abstract state”
Defines an interface which encapsulates all state-specific behaviours
Delegates the execution of its state-specific behaviour

Concrete State

Any number of concrete states.
Each state encapsulates its behaviour.

Creating Components for the State Pattern

Define the possible states
Conditions for transitioning between states
Define the initial state

Courses

C# Design Patterns: State

References