State Pattern

Prakash Sharma
2 min readNov 3, 2022

--

This is the second blog in the series of design patterns and today we will be understanding how state pattern works.

My previous design pattern blogs —

The state pattern is the behavioral design pattern that alters the behavior of the object when its internal state changes.

Problem statement — Implement a connection service class that transfers/receives the file over multiple modes such as the Internet, Bluetooth, wifi, etc. The class should extensible so that if we want to add any other modes then it should be possible.

The basic approach that can be used and comes in mind is something like the below

In this class, we have an enum that decides the internal state of our Connection service class, so if the connection type is internet it will compare in our switch case, and based on that it will transfer the data over the internet.

Problems with the above approach —

  • We have a switch statement that does the comparison checks, it will create maintainability issues in the longer run.
  • It violates the Open Closed Principle as if we want to add any other mode such as Email then we have to modify this class and add the case of Email then also we have to add the Email type in our ConnectionType enum.
  • The system is not extensible, it’s hard to add and remove modes of transfer.

Solution — We are going to use the state pattern to solve this problem.
We will provide the abstraction over the connection type so that our ConnectionService class will be independent of the actual connection, it will make our connection service class closed for modification and at the same time, it will let another connection type extend from the Connection. So we can say it follows the open closed principle.

This interface defines the contract for our different connection types.

Similarly, we have other modes such as wifi and Bluetooth.

Now let’s see the actual state connection service class.

Note that our class is pretty clean now and is more maintainable.

Result section -

Please do clap 👏 if you liked the content and if there is any suggestion let me know in the comments.

My previous design pattern blogs —

Keep coding ⌨️.

GitHub Link — State pattern

--

--