State Design Pattern [Behavioral]

The core idea is to create an object-oriented state machine. The state design pattern can be applied successfully to remove complex conditional logic from a software system.

  • The conditional behavior gets encapsulated into separate types.
  • There will be dedicated types which results in a more flexible system.
  • Makes our code easier to understand.
  • Adding new states or updating existing ones will require less effort.

There are 3 parts: The context, State interface, Concrete types.

The context exposes the public interface to the callers; it delegates requests to its state. The state protocol defines the common interface for all concrete states. Finally, the concrete state types implement the behavior associated with the state of the context. Each state type provides its own implementation for a request, thus the context behavior will be different whenever its state changes.

The state design pattern allows an object to behave differently when its internal state changes.

Example:

  1. States when user withdraws money from an ATM machine
  2. States during the process of user buying something on an e-commerce platform

The state design pattern allows objects to behave differently as their internal state changes. It can be applied successfully to remove monolithic conditional logic from a software system.

To implement the state pattern, you need to identify the steps that cause changes in the behavior of an object. Then, extend these steps and encapsulate them into dedicated state types.

Disadvantage of State Pattern is exposing the states to clients. The state types should be used exclusively by the context, whereas clients should interact with the interface provided by the context.

Advertisements

One thought on “State Design Pattern [Behavioral]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s