Skip to content
APPCITORThe Tech Blog
Esc

Behavioral – State Design Pattern

August 16, 2020 1 min read

Behavioral – State Design Pattern

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

Singleton Design Pattern

Factory Design Pattern

Abstract Factory Design Pattern

Prototype Design Pattern

Builder Design Pattern

Structural Design Patterns

Facade Design Pattern

Decorator Design Pattern

Adapter Design Pattern

Bridge Design Pattern

Composite Design Pattern

Proxy Design Pattern

Flyweight Design Pattern

Share this article

Keep reading