1 of 7

State Design Pattern �(Behavioral)

Thanh Le – Software Architect / Technical Consultant

Complexity: 1/3

Popularity: 2/3

2 of 7

Intent

State is a behavioral design pattern that lets an object alter its behavior when its internal state changes. It appears as if the object changed its class.

Image source: internet

3 of 7

Problem

Imagine that we have a Document class. A document can be in one of three states: Draft, Moderation and Published. The publish method of the document works a little bit differently in each state:

  • In Draft, it moves the document to moderation.
  • In Moderation, it makes the document public, but only if the current user is an administrator.
  • In Published, it doesn’t do anything at all.

Image source: internet

4 of 7

Solution

The State pattern suggests that you create new classes for all possible states of an object and extract all state-specific behaviors into these classes.

�Instead of implementing all behaviors on its own, the original object, called context, stores a reference to one of the state objects that represents its current state, and delegates all the state-related work to that object.

�To transition the context into another state, replace the active state object with another object that represents that new state. This is possible only if all state classes follow the same interface and the context itself works with these objects through that interface.

��

5 of 7

Structure

Image source: internet

  • Context – defines an interface for clients to interact. It maintains references to concrete state objects, which you may use to define their current state. The context communicates with the state object via the state interface.

  • State – defines an interface for declaring what each concrete state should do.

  • Concrete State – provides an implementation for the methods defined in the state.

6 of 7

Pros/Cons

  • Single Responsibility : Organize the code related to particular states into separate classes.
  • Open/Closed: We can introduce new states without changing existing state classes or the context.�

  • Applying the pattern can be overkill if a state machine has only a few states or rarely changes.

7 of 7

Practice

https://github.com/thanhle0212/23GoF-Design-Patterns-CSharp