1 简介
状态模式(State Pattern)定义:允许一个对象在其内部状态改变时改变它的行为,对象看起来修改了它所属的类。
环境类(Context)又称上下文类,它是拥有状态(State)的对象,但是由于其状态存在多样性,且在不同状态下对象的行为有所不同,因此将状态独立出去,形成单独的状态类。
2 代码
(1)环境类(Context)
public class Context {
private State state;
public void setState(State state) {
this.state=state;
}
public void handleA() {
state.handleA();
setState(new StateB());
}
public void handleB() {
state.handleB();
setState(new StateA());
}
}
(2)抽象状态类(State)
public abstract class State {
public void handleA() {
throw new UnsupportedOperationException("Error:StateB hasn't \"handleA()\" method");
}
public void handleB() {
throw new UnsupportedOperationException("Error:StateA hasn't \"handleB()\" method");
}
}
(3)具体状态类(ConcreteState)
public class StateA extends State{
@Override
public void handleA() {
System.out.println("处理状态A,并切换到状态B");
}
}
public class StateB extends State{
@Override
public void handleB() {
System.out.println("处理状态B,并切换到状态A");
}
}
(4)客户端类(Client)
public class Client {
public static void main(String[] args) {
Context context=new Context();
context.setState(new StateA());
context.handleA();
context.handleB();
context.handleA();
}
}
处理状态A,并切换到状态B
处理状态B,并切换到状态A
处理状态A,并切换到状态B