State pattern is a type of Behavioral Pattern and is used to change the behavior of the objects as per the requirement. The state of the object can be changed using if-else conditions. Loose-coupling and systematic approach for implementing the context and state can be done using the State Pattern.
Advantages
Responsibilities between objects and relationships can be managed easily.
Same object can be used for different implementations.
Conceptual
figure
Context: Context is having a number of internal states. Whenever the request() is made to the Context, it calls the State for handling.
State: State is aninterface that defines a common interface for all concrete states.
ConcreteState: Concrete class implements its own implementation for the request.
Examples
[java]
public interface Emotions
{
public String sayHai();
public String saybye();
}
public class HappyState implements Emotions
{
public String saybye()//overrides with interface methods
{
return "Bye, friend!";
}
public String sayHai()
{
return "Hello, friend!";
}
}
public class SadState implements Emotions
{
public String saybye()//overrides with interface methods
{
return "Bye. Sniff, sniff.";
}
public String sayHai()
{
return "Hai. Sniff, sniff.";
}
}
public class Person implements Emotions
{
Emotions emotionalState;
public Person(Emotions emotionalState)
{
this.emotionalState = emotionalState;
}
public void setEmotionalState(Emotions emotionalState)
{
this.emotionalState = emotionalState;
}
public String saybye()
{
return emotionalState.saybye();
}
public String sayHai()
{
return emotionalState.sayHai();
}
}
public class StatePattern
{
public static void main(String[] args)
{
Person person = new Person(new HappyState());//creating object for person class
System.out.println("Hello in happy state: " + person.sayHai());
System.out.println("Goodbye in happy state: " + person.saybye());
person.setEmotionalState(new SadState());
System.out.println("Hai in sad state: " + person.sayHai());
System.out.println("bye in sad state: " + person.saybye());
}
}[/java]
In the above example, an interface(Emotions) is created and that interface is implemented by two class(Sadstate and Happystate). The main class(StatePattern) creates objects for the implemented classes.
The benefits of using State Pattern is clearly explained in the above example. Polymorphic behavior is implemented, the scope for errors is very low and it is simple to add more states for additional behavior, thus making it more robust, easily maintainable and flexible. Also, the State Pattern helps in avoiding if-else or switch-case conditional logic.
Output
The result will be as follows.
[java] Hai in happy state: Hai, friend!
bye in happy state: Bye, friend!
Hai in sad state: Hai. Sniff, sniff.
bye in sad state: Bye. Sniff, sniff.[/java]
Summary
Key Points
Object state can be changed easily.
Same object can be modified as per the requirement.