Behavioral – State Design Pattern
August 16, 2020 1 min read

State pattern is one of the behavioral design patterns that used when an object changes its behavior based on its internal state. Suppose you want to change behavior of an object based on its state. For that we can have a state variable in the object and use if-else condition block to perform different actions based on the state.
Let’s see an example on state design pattern
Assume that you set a sound for alert coming for missed calls in your mobile phone and next you wanted to change the alert mode to vibration for the messages in the mobile phone. So the mobile phone will change the state for the necessary time like below.

This is the state interface to give the state of the alert as the output. This is the wrapper class. But you can see for this interface you need the class “AlertStateContext”. Let’s see what is that class.

Here the “AlertStateContext” class is the state base class that replicates the methods of the state machine interface “AlertState”. Each method takes one additional parameter: an instance of the wrapper class. The State base class specifies any useful “default” behavior.

These “Sound” and “Vibration” are the derived class for each domain state. These derived classes only override the methods they need to override.
The wrapper class maintains a “current” State object.
Let’s see the main method.

Here state methods change the current state in the wrapper object as appropriate.
Output:

You can visit the below given articles to learn about creational design patterns and Structural Design Patterns.
Thank you.
Creational Design Patterns
Abstract Factory Design Pattern
Structural Design Patterns


