Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Info

The State Design Pattern is one of the behavioral design patterns that allows an object to alter its behavior when its internal state changes, appearing as if the object has changed its class.

...

The central idea of the State Pattern is to represent the different "states" of a state machine (which represents the different states an object can be in) with different classes. In the State pattern, the state machine is typically implemented as a set of enumerated states, while the actual state behavior is delegated to delegate objects representing the different states.

Here is a more detailed breakdown:

  1. Context: This is the class that has a property whose value is based on the current state of the object. It delegates the state-specific behavior to the State object.

  2. State Interface/Abstract Class: This is an interface that defines the methods which should be implemented by all concrete state classes.

  3. Concrete State Classes: These are classes that implement the State interface and provide the state-specific behavior.

Let's use a simple real-world example - a TV Remote Control:

Code Block
languagejava
// State Interface
public interface State {
   public void doAction();
}

// Concrete State classes
public class TVStartState implements State {
   @Override
   public void doAction() {
      System.out.println("TV is turned ON");
   }
}

public class TVStopState implements State {
   @Override
   public void doAction() {
      System.out.println("TV is turned OFF");
   }
}

// Context class
public class TVContext implements State {
   private State tvState;

   public void setState(State state) {
      this.tvState=state;
   }

   public State getState() {
      return this.tvState;
   }

   @Override
   public void doAction() {
      this.tvState.doAction();
   }
}

You can use it like this:

Code Block
languagejava
public class TVRemote {
   public static void main(String[] args) {
      TVContext context = new TVContext();
      State tvStartState = new TVStartState();
      State tvStopState = new TVStopState();

      context.setState(tvStartState);
      context.doAction();

      context.setState(tvStopState);
      context.doAction();
   }
}

This will output:

Code Block
TV is turned ON
TV is turned OFF

The State pattern can be very useful in scenarios where an object's behavior depends on its state, and it must be able to change its behavior at runtime depending on that state. It is a clean way for an object to partially change its behavior without resorting to large monolithic conditional statements.