Versions Compared

Key

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

...

  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:

...

languagejava

...

  1. .

...

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:

...

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.