state design pattern — get the gist in 2 min

aditya chaudhari
JavaDeveloperDiary — JDD
2 min readApr 18, 2023
state design pattern java

Do you have many if-else conditions in your class ? Is your object has many states and behaviors which you have intent to encapsulate, then you must think about using either state or strategy pattern.

Both are behavioral design patterns, interestingly UML diagram is also same for both of them but their Intent is different.

please check this for strategy pattern and below let’s check how state pattern can be useful to us.

State pattern is helpful when an object’s behavior is dependent on its state, and the behavior needs to change based on the changes in its internal state. In this post, we’ll explore the state design pattern in Java and see how it can be implemented.

Simple Example Scenario :
Consider an online order management system where an order can have several states like “new”, “shipped”, “delivered” or “cancelled”. Depending on the current state of the order, the available actions or behavior will be different. In this case, we can use the state pattern to encapsulate the behavior associated with each state into separate classes and then delegate the behavior based on the current state of the object.

Solution and structure :
Without the state pattern, the approach would be to create multiple if-else in the order class itself, however, with the state pattern we can create an order class and as per the order state we can delegate the request for a different operation to respective state classes.
click here for github code link

state design pattern UML — source (wiki)

For the UML above, below are the classes we are going to create
state interface : OrderState
state concrete classes :
NewOrderState, ShippedOrderState, DeliveredOrderState, CancelledOrderState
context class : Order
Main client class : StatePatternMain .

click here for github code link

In the Strategy pattern, the client code has the responsibility of selecting the appropriate strategy object at runtime. In the State pattern, the state transitions are usually triggered by the object’s internal state changes and the object transitions from one state to another automatically.

The real fun is in the details, if you wish to know pros and cons of state pattern, java code examples please consider visiting my detailed article at [state-design-pattern-java-explained-8-min-read]

Thanks for reading. Love IT, Live IT, Enjoy IT.

Every Tuesday I am writing an exciting technical article, please consider follow if you wish to get notified!

--

--

aditya chaudhari
JavaDeveloperDiary — JDD

building efficient, scalable and maintainable enterprise e-commerce applications using java, spring framework and SAP CC. Life Mantra → Love IT Live IT Enjoy IT