Monday 4 November 2013

State Design Pattern (Behavioral Pattern)

State Pattern

In nutshell, State Pattern allow us to have a configurable behavior of the object by composition. This behavior is configured when some state member of object is changed. Usually this behavior is provided when object change its state and some property setter is called.

If the method of the class are partitioned on the basis of STATE of an instance variable, then State Design Pattern is the answer. All the switches in the methods that change the method behaviour based on the current state, is a code smell that should be re-factored to the State Pattern.

For all different states, we define separate classes those comply an Interface

Composition + Delegate based solution is applied to handle different state based methods of a class

When the state is changed, and the State Setter Method is called, the Composition-Delegate based
instance variable is also changed.Now the setter will instantiate the Composition-Delegation based 
instance variable. This will result in State Setter having IF-Else/Switch for the initialising the 
instance variable. This can be solved by the Simple Factory variation of Factory Design Pattern.


State Pattern + Factory Pattern are used in combination 
Different State based classes are the Family of Classes those are created by factory design pattern 
while implementing the State Pattern.

No comments:

Post a Comment