Java Tutorial/Design Pattern/State Pattern
Simple demonstration of the State pattern.
<source lang="java">
interface State {
void operation1(); void operation2(); void operation3();
} class ServiceProvider {
private State state; public ServiceProvider(State state) { this.state = state; } public void changeState(State newState) { state = newState; } public void service1() { state.operation1(); state.operation3(); } public void service2() { state.operation1(); state.operation2(); } public void service3() { state.operation3(); state.operation2(); }
} class Implementation1 implements State {
public void operation1() { System.out.println("Implementation1.operation1()"); } public void operation2() { System.out.println("Implementation1.operation2()"); } public void operation3() { System.out.println("Implementation1.operation3()"); }
} class Implementation2 implements State {
public void operation1() { System.out.println("Implementation2.operation1()"); } public void operation2() { System.out.println("Implementation2.operation2()"); } public void operation3() { System.out.println("Implementation2.operation3()"); }
} public class StateDemo {
static void run(ServiceProvider sp) { } public static void main(String args[]) { ServiceProvider sp = new ServiceProvider(new Implementation1()); sp.service1(); sp.service2(); sp.service3(); sp.changeState(new Implementation2()); sp.service1(); sp.service2(); sp.service3(); }
}</source>
State: changing object behavior
<source lang="java">
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(); }
}</source>