Monday, May 1, 2017

State Design Pattern

State Design Pattern


If you are a programmer, Design Pattern are some main aspects that you need to study and grow up on. Even though number of Design-Pattern exists in this article we are going to explore a Behavioral Design Pattern called State Pattern

According to Wikipedia  state pattern is a behavioral software design pattern that implements a state machine in an object-oriented way. With the state pattern, a state machine is implemented by implementing each individual state as a derived class of the state pattern interface, and implementing state transitions by invoking methods defined by the pattern's super-class.

If you are familiar with State Machines, then State Pattern is not a harder aspect that you cannot master. State Pattern is well suited when the behavior of an object changes in accordance with the internal state of the object.  So, if anyone wants to build an Object-Oriented State Machine, then the most suitable structure to be used is State Pattern.

Structure of State Pattern


In State Pattern we have an 'Context' class which interact with client. You can think of this like the 'State Machine'. Then define an 'State' Abstract Class. Implement this class for different states that the Machine should change. Define an Abstract State Specific Behavior in 'State' class and override it in every sub-class. Have a pointer to 'Current State' inside the 'Context' Class. When the internal state of the machine should change, adjust the 'Current State' pointer to the next specified state of the machine. 

State Pattern does not specify where state transitions will be defined. There are two choices: inside the 'Context' class or Each individual state derived class. Advantage of the latter is that we can add new states easily. But each State derived class has knowledge of its siblings, which introduces a dependency between sub-classes.  

Here is the Class Diagram for State Pattern.


Is it a Good Choice ? 


Any concept is a good choice in its own domain. So, use this Pattern if an only if the behavior of objects in the domain is dependent of the internal state of the object.
Here is a code example for State Pattern. 


No comments:

Post a Comment