The State Pattern in Java

Introduction to the State Pattern

Design pattern in a simple meaning, is a way to design reusable object-oriented code. We can think of ways to design our classes, interfaces, enums and their members so that the code is reusable but flexible.

There are 23 most important design patterns, pioneered by the book Design Patterns: Elements of Reusable Object-Oriented Software, written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides or Gang of Four for short. We will cover these design pattern one by one.

By the original GoF definition, the State pattern allows an object to alter its behavior when its internal state changes.The object will appear to change its class. The State pattern includes components:

– State: an interface to define the general action for each state.

– Concrete State: a class that encapsulates each state.

– Context: this contains the instance of the current state.

Implementation of State Pattern in Java

Say a phone has three states when someone calls it: silence, ringing or vibration. First we create a State interface

public interface State {
  void showState();
}

And next we create three concrete state classes. The RingingState.java:

public class RingingState implements State{
  public void showState() {
    System.out.println("Phone is in ringing mode");
  }
}

The SilenceState.java

public class SilenceState implements State{
  public void showState() {
    System.out.println("Phone is in silence mode");
  }
}

The VibrationState.java

public class VibrationState implements State{
  public void showState() {
    System.out.println("Phone is in vibration mode");
  }
}

And in Test.java

public class Test {
  public static void main(String[] args){
    PhoneContext context = new PhoneContext(
        new RingingState());
    context.showState();
    context.setState(new SilenceState());
    context.showState();
    context.setState(new VibrationState());
    context.showState();
  }
}

The output will be:

Phone is in ringing mode
Phone is in silence mode
Phone is in vibration mode

Leave a Reply