在状态模式(State Pattern)中,类的行为是基于它的状态改变的。
模式中的角色
上下文环境(Context):它定义了客户程序需要的接口并维护一个具体状态角色的实例,将与状态相关的操作委托给当前的Concrete State对象来处理。
抽象状态(State):定义一个接口以封装使用上下文环境的的一个特定状态相关的行为。
具体状态(Concrete State):实现抽象状态定义的接口。
State
package design.pattern.state;public abstract class State { protected Context context; public State(Context context) { this.context = context; } public abstract Context handler();}
Context
package design.pattern.state;public class Context { private State state; public Context() { this.state = new ConcreteStateA(this); } public void setState(State state) { this.state = state; } public Context action() { state.handler(); return this; }}
ConcreteContextA
package design.pattern.state;public class ConcreteStateA extends State { public ConcreteStateA(Context context) { super(context); } @Override public Context handler() { System.out.println("ConcreteStateA"); context.setState((new ConcreteStateB(context))); return context; } }
ConcreteContextB
package design.pattern.state;public class ConcreteStateB extends State { public ConcreteStateB(Context context) { super(context); } @Override public Context handler() { System.out.println("ConcreteStateB"); return context; }}
Client
package design.pattern.state;public class Client { public static void main(String[] args) { new Context().action().action().action(); }}