Java Behavioral Design Patterns – State Design Pattern

State design pattern is used when the behavior of an Object changes based on its internal state.

In the state pattern, a state machine is implemented by implementing each individual state as a derived class of the state pattern interface, each class which implements the state interface defines a method in its own way to change the state of the object. The key points to remember for this pattern are:

  • An object should change its behavior when its internal state changes.
  • Each state should be defined independently.
  • Adding new states should not affect the other states or functioning.

<Here are ALL other Java Design Patterns, explained in detail with examples>

State Design Pattern by Example

Let us understand this pattern with an example. The best and simple example would be of Car or any vehicle. The car is controlled by one of the key events, Changing Gears.

For our example, we will define GearState as our State interface.

To keep the illustration to the minimum, we will only consider the 2 gear system. Now let us define our gears.

FirstGear

Above class implements the changeGear method from GearState. Also, it provides some convenient methods for understanding.

SecondGear

Below is our implementation of Car context.

Notice how the car accelerate method is implemented. It’s clearly influenced by the internal state of gear the car is in.

Running  the example

And here is the output:

 Conclusion

In this article, we have seen that this pattern is very much simple to implement. Instead of writing multiple if-else statements it becomes much easier to encapsulate each of these set of statements into separate classes of their own. Furthermore, the implementation of each state can thus differ independently of the other states. We can easily increase the number of states without modifying other states which makes this pattern maintainable and flexible.

You can download the code from our GitHub repository:

Download from Git

 

<Here are ALL other Java Design Patterns, explained in detail with examples>

Add a Comment

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