标签:
好处:将与特定状态相关的行为局部化,并将不同状态的行为分割开来。
当一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,就可以考虑使用状态模式。
/** * Created by hero on 16-4-4. */ public abstract class State { public abstract void handle(Context context); } /** * Created by hero on 16-4-4. */ public class ConcreteStateA extends State { @Override public void handle(Context context) { System.out.println("state a"); context.setState(new ConcreteStateB()); context.request(); } } /** * Created by hero on 16-4-4. */ public class ConcreteStateB extends State { @Override public void handle(Context context) { System.out.println("state b--->the end state"); //context.setState(new ConcreteStateA()); } } /** * Created by hero on 16-4-4. */ public class Context { private State state; public void request() { state.handle(this); } public Context(State state) { this.state = state; } public State getState() { return state; } public void setState(State state) { this.state = state; } } public class Main { public static void main(String[] args) { Context context = new Context(new ConcreteStateA()); context.request(); } }
标签:
原文地址:http://www.cnblogs.com/littlehoom/p/5353122.html