State Design Pattern

This week I continued with implementing different Tree data structures in Pharo, and have investigated the state design pattern as a good way of having a single class that can act as both an empty tree and a normal tree. In this blog post I will briefly describe the State Design Pattern and its applications. The state pattern is very closely related to the strategy and bridge design patterns. The Null object pattern that I described in a previous blog post can be regarded as a special case of the state pattern.

Introduction

State design pattern is one of the behavioral design patterns where a class object has an internal state, and based on this state the object can change its behavior i.e. act as an object of some other class. Next figure shows a general structure of the state design pattern.

In the previous picture, Context represents the interface which is provided to the client of the program. Context refers to the State interface for performing state-specific operations (e.g. handle()). State defines the interface, which ConcreteStateA and ConcreteStateB implement.

ConcreteStateA and ConcreteStateB represent different states and their handle() method defines a different behavior.

The following image, taken from the Source Making website, nicely illustrates the state design pattern.

In this example the vending machine has two states and when money is deposited (VendingDepositeState), it will change its state and return the bought item (VendingStockState).

Advantages and disadvantages

**Advantages: **

Disadvantages:

Conclusion

State design pattern is an excellent way to avoid unnecessary if-checks and move the state-specific block into its own class and use polymorphism. The behavior of the object can easily be changed by providing a reference to a new state, and an existing code can easily be extended to provided different behaviors. The only drawback is higher memory requirements which can easily be eliminated by using other design patterns - i.e. the Singleton pattern.

Images

Images are taken from Wikipedia and Source Making. Link is provided in-text.