State: changing object behavior : State Pattern « Design Pattern « Java Tutorial






interface Animal {
  String talk();
}

class Frog implements Animal {
  public String talk() {
    return "ggg!";
  }
}

class Cat implements Animal {
  public String talk() {
    return "miao";
  }
}

class Creature {
  private Animal state = new Frog();

  public void greet() {
    System.out.println(state.talk());
  }
  public void toCat() {
    state = new Cat();
  }
}

public class MainClass {

  public static void main(String args[]) {
    Creature creature = new Creature();
    creature.greet();
    creature.toCat();
    creature.greet();
  }
}








34.17.State Pattern
34.17.1.State: changing object behavior
34.17.2.Simple demonstration of the State pattern.