Behavioural Design Pattern: State Design pattern

Level : Advanced
Mentor: Shailendra Chauhan
Duration : 00:01:00

Define State Design Pattern

This pattern is used to change the behavior of an object when its internal state changes. Here, an object is built to represent several states, as well as a context object whose behavior changes as its state object does.

Examples of State Design Patterns

Examples of the state design pattern include

  • Navigation
  • Validations

State Pattern with UML diagram

The classes, interfaces, and objects in the above UML class diagram are defined as follows.

  • Context: This is a class that contains a concrete state object and provides behavior based on its current state. This is utilized by clients.
  • State: This interface allows the Context object to access the changing functionality.
  • ConcreteStateA/B: These classes implement the State interface and offer the actual functionality that will be used by the Context object. Each concrete state class defines behavior for a specific state of the Context object.

When should you use the State Design Pattern?

The Strategy design pattern is applicable in the following scenarios:

  • An object's behavior changes depending on its state.
  • Maintain flexibility in assigning requests to handlers.
  • An object is becoming more complex, with multiple conditional behaviors.

Advantages of the State Design Pattern

  • State-Based Behaviour Encapsulation: State classes contain functionality that is distinct to each state.
  • Easy to Add New States: Adding new states does not necessitate modifying the context or other states.
  • Eliminates Conditional Statements: It helps in the elimination of conditional statements for state-dependent behavior changes.
  • Maintainability & flexibility: The state pattern facilitates the maintenance and extension of state-based behavior.
  • Dynamic Behaviour Change: The context's behavior can change during runtime based on its state.
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this