当一个对象内在状态改变时运行其改变行为,这个对象看起来像改变了其类
state - 抽象状态角色
接口或抽象类,负责对象状态定义,并且封装环境角色以实现状态切换。
concresteState - 具体状态角色
每一个具体状态必须完成两个职责: 本状态的行为管理以趋向状态处理
context 环境角色
客户端需要的端口 并且付诸具体状态的切换
状态模式相对来说比较复杂,它提供了一种物质运动的另一个观察视角,通过状态变更促使行为的变化
public class Client {
public static void main(String[] args) {
Context context = new Context();
context.setLiftState(new CloseState());
context.run();
context.open();
}
}
public abstract class LiftState {
protected Context context;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public abstract void open();
public abstract void close();
public abstract void run();
public abstract void stop();
}
public class Context {
public final static OpenState openState = new OpenState();
public final static CloseState closeState = new CloseState();
public final static RunningState runningState = new RunningState();
public final static StoppingState stopping = new StoppingState();
private LiftState liftState;
public LiftState getLiftState() {
return liftState;
}
public void setLiftState(LiftState liftState) {
this.liftState = liftState;
this.liftState.setContext(this);
}
public void open(){
this.liftState.open();
}
public void close(){
this.liftState.close();
}
public void run(){
this.liftState.run();
}
public void stop(){
this.liftState.stop();
}
}
public class CloseState extends LiftState{
@Override
public void close() {
System.out.println("关闭");
}
@Override
public void open() {
super.context.setLiftState(Context.openState);
super.context.getLiftState().open();
}
@Override
public void run() {
super.context.setLiftState(Context.runningState);
super.context.getLiftState().run();
}
@Override
public void stop() {
super.context.setLiftState(Context.stopping);
super.context.getLiftState().stop();
}
}
public class OpenState extends LiftState{
@Override
public void close() {
super.context.setLiftState(Context.closeState);
super.context.getLiftState().close();
}
@Override
public void open() {
System.out.println("打开");
}
@Override
public void run() {
}
@Override
public void stop() {
// TODO Auto-generated method stub
}
}
public class RunningState extends LiftState {
@Override
public void close() {
}
@Override
public void open() {
}
@Override
public void run() {
System.out.println("正在运行");
}
@Override
public void stop() {
super.context.setLiftState(Context.stopping);
super.context.getLiftState().stop();
}
}
public class StoppingState extends LiftState {
@Override
public void close() {
}
@Override
public void open() {
super.context.setLiftState(Context.openState);
super.context.getLiftState().open();
}
@Override
public void run() {
super.context.setLiftState(Context.runningState);
super.context.getLiftState().run();
}
@Override
public void stop() {
System.out.println("停止运行...");
}
}