State Design Pattern in Java

As this pattern closely follows the behaviour of a particular object, State Design Pattern falls under the Behavioural Design Pattern section. This pattern studies any behavioural changes in an object that will subsequently cause its state to change as well. Lower coupling is promoted when this pattern is implemented. If the context object changes its behaviour depending on the internal state, there might arise run-time errors if that object is tightly coupled to state derived classes.

Definition

As defined in the Gang of Four book, the State Design Pattern ‘allows an object to change its behaviour when there is a significant change in the internal state of the same object.’

A simple way in which this can implemented is by introducing a flag variable in the object that will check its state after every function it performs. Whenever a change is noticed, a simple if-else block will respond to it by making changes to its behaviour.

Example and Code

This is a simple code of a burglar alarm. The burglar alarm will have two states: ringing and silent. When it detects unwanted motion, it will start ringing. Otherwise, it will be silent for other states.

public interface Burglar
{ public void trigger(TriggerAlert trig); }

class TriggerAlert
{
private BurglarAlarm presentState;
public TriggerAlert() {
presentState = new Sound(); }
public void setState (BurglarAlarm state)
{ presentState = state; }

public void bell()
{ presentState.trigger(this);
}
}

class Ring implements Burglar
{
@override
public void trigger(TriggerAlert trig)
{
System.out.println(“Burglar Ring”);

class Silent implements Burglar
{
@override
public void trigger(TriggerAlert trig)
{
System.out.println(“No movement detected. Do not Ring”);
}
}

When to use the State Design Pattern

If a certain object’s behaviour is governed by the present state it is in during run-time, this pattern completely matches the requirement. As mentioned before, loose coupling is achieved as the object is not dependent on complex switch case statements neither does it require long if-else blocks to make the necessary changes.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.