State Design Pattern in Java

By | July 7, 2020

In this post, We will talk and learn about the State Design Pattern in Java.

Key Points About StateDesign Pattern :

  • State design pattern falls under behavioral design pattern. This Pattern is used when an Object changes its behavior based on its internal state.
  • The main benefit of using the State pattern to implement polymorphic behavior. The chances of error are very less and it’s very easy to add more states for additional behaviors. Thus making our code more robust, easily maintainable, and flexible. 

Now Let’s move towards the implementation of the State Design Pattern.

Use Case:

Suppose we want to implement an AC Remote with a simple button to perform an action. If the State is ON, it will turn on the AC and if the state is OFF, it will turn off the AC.

Below is the complete source code:

State Design Pattern

State.java

 

ACStartState.java

 

ACStopState.java

 

ACContext.java

 

ACRemoteTest.java

Output of This Program:

AC is turned ON
——————————-
AC is turned OFF

You May Also Like:

Singleton Design Pattern in java
Prototype Pattern in Java
Factory Pattern in Java
Abstract Factory Pattern in Java
Builder Pattern in Java
Adapter Design Pattern in Java
Decorator Design Pattern in Java
Facade Design Pattern in Java
Bridge Design Pattern in Java.
Command Design Pattern in Java

That’s all about the State Design Pattern in Java.
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *