1.定义#
当一个对象内在状态改变时允许其改变行为,这个对象看起来像改变了其类。每个状态一个实现类,状态的切换实则为类之间的切换。不同的状态类负责本状态的逻辑和状态转换。委托统一的上下文类来控制整个过程。
2.类图#
3.实现#
3.1抽象状态类##
public abstract class State {
protected Context context;
public void setContext(Context _context) {
this.context = _context;
}
public abstract void handler1();
public abstract void handler2();
}
3.2具体状态类##
public class ConcreteState1 extends State {
@Override
public void handler1() {
System.out.println("处于状态1");
}
@Override
public void handler2() {
System.out.println("转移向状态2");
super.context.setState(Context.concreteState2);
super.context.handler2();
}
}
public class ConcreteState2 extends State {
@Override
public void handler2() {
System.out.println("处于状态2");
}
@Override
public void handler1() {
System.out.println("转移向状态1");
super.context.setState(Context.concreteState1);
super.context.handler1();
}
}
3.3上下文类##
public class Context {
private State state;
public static final ConcreteState1 concreteState1 = new ConcreteState1();
public static final ConcreteState2 concreteState2 = new ConcreteState2();
public void setState(State state) {
this.state = state;
this.state.setContext(this);
}
public void handler1() {
this.state.handler1();
}
public void handler2() {
this.state.handler2();
}
}
3.4客户端类##
public class Client {
public static void main(String args[]) {
Context context = new Context();
context.setState(Context.concreteState1);
context.handler2();
context.handler1();
}
}