Java Design Patterns State Patterns

Introduction

State Patterns allow an object to alter its behavior when its internal state changes.

Use case

  • Vending Machine

Example

abstract class Controller {
   public abstract void pressSwitch(Laptop context);
}

class Off extends Controller {
   @Override/*w w w . j ava  2s .c o  m*/
   public void pressSwitch(Laptop context) {
      System.out.println("I am Off .Going to be On now");
      context.setState(new On());
   }
}

class On extends Controller {
   @Override
   public void pressSwitch(Laptop context) {
      System.out.println("I am already On .Going to be Off now");
      context.setState(new Off());
   }
}

class Laptop {
   private Controller state;

   public Controller getState() {
      return state;
   }

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

   public Laptop(Controller state) {
      this.state = state;
   }

   public void pressButton() {
      state.pressSwitch(this);
   }
}

public class Main {
   public static void main(String[] args) {
      Off initialState = new Off();
      Laptop laptop = new Laptop(initialState);

      laptop.pressButton();

      laptop.pressButton();
   }
}



PreviousNext

Related