package com.jmj.pattern.state.after;public abstract class LiftState {protected Context 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();}
package com.jmj.pattern.state.after;public class Context {public final static OpeningState OPENING_STATE =new OpeningState();public final static ClosingState CLOSING_STATE =new ClosingState();public final static RunningState RUNNING_STATE =new RunningState();public final static StoppingState STOPPING_STATE =new StoppingState();private LiftState liftState;public LiftState getLiftState() {return liftState;}public void setLiftState(LiftState liftState) {this.liftState = liftState;//设置当前状态对象的context对象liftState.setContext(this);}public void open(){this.liftState.open();}public void stop(){this.liftState.stop();}public void run(){this.liftState.run();}public void close(){this.liftState.close();}}
package com.jmj.pattern.state.after;public class OpeningState extends LiftState{@Overridepublic void open() {System.out.println("电梯开启...");}@Overridepublic void close() {super.context.setLiftState(Context.CLOSING_STATE);super.context.close();}@Overridepublic void run() {//什么都不做}@Overridepublic void stop() {//什么都不做}
}
package com.jmj.pattern.state.after;public class RunningState extends LiftState{@Overridepublic void open() {//什么都不做}@Overridepublic void close() {//什么都不做}@Overridepublic void run() {System.out.println("电梯运行...");}@Overridepublic void stop() {super.context.setLiftState(Context.STOPPING_STATE);super.context.stop();}
}
package com.jmj.pattern.state.after;public class StoppingState extends LiftState{@Overridepublic void open() {super.context.setLiftState(Context.OPENING_STATE);super.context.open();}@Overridepublic void close() {super.context.setLiftState(Context.CLOSING_STATE);super.context.close();}@Overridepublic void run() {super.context.setLiftState(Context.RUNNING_STATE);super.context.run();}@Overridepublic void stop() {System.out.println("电梯停止...");}
}
package com.jmj.pattern.state.after;public class ClosingState extends LiftState{@Overridepublic void open() {super.context.setLiftState(Context.OPENING_STATE);super.context.open();}@Overridepublic void close() {System.out.println("电梯关闭...");}@Overridepublic void run() {super.context.setLiftState(Context.RUNNING_STATE);super.context.run();}@Overridepublic void stop() {super.context.setLiftState(Context.STOPPING_STATE);super.context.stop();}
}
package com.jmj.pattern.state.after;public class Client {public static void main(String[] args) {Context context = new Context();context.setLiftState(Context.STOPPING_STATE);context.run();context.stop();context.open();context.close();context.run();}
}