把过于复杂的条件判断转移到不同状态的一系列类之中,使逻辑简化.
当一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,就可以使用状态模式.
1 2 3 4 5 6 7 8 9
| package state;
public abstract class State { public abstract void handle(Context context); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| package state;
public class Morning extends State { public void handle(Context context) { System.out.println("精神饱满"); context.setCurrent(new Noon()); context.work(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| package state;
public class Noon extends State { public void handle(Context context) { System.out.println("累了"); context.setCurrent(new Afternoon()); context.work(); } }
|
1 2 3 4 5 6 7 8 9 10 11
| package state;
public class Afternoon extends State { public void handle(Context context) { System.out.println("高高兴兴下班去"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package state;
public class Context { private State current;
public Context() { current = new Morning(); }
public void work() { current.handle(this); }
public State getCurrent() { return current; }
public void setCurrent(State current) { this.current = current; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package state;
public class Main { public static void main(String[] args) { Context context = new Context();
context.work();
context.setCurrent(new Noon()); context.work(); } }
|