设计模式----状态模式(state pattern)
LiftState.java代码如下:
package com.designPattern.state;public abstract class LiftState {protected Context context;public abstract void open();public abstract void close();public abstract void run();public abstract void stop();public Context getContext() {return context;}public void setContext(Context context) {this.context = context;}}
package com.designPattern.state;public class ClosingState extends LiftState{@Overridepublic void open() {super.context.setLiftState(Context.openningState);super.context.getLiftState().open();}@Overridepublic void close() {System.out.println("电梯门关闭");}@Overridepublic void run() {super.context.setLiftState(Context.runningState);super.context.getLiftState().run();}@Overridepublic void stop() {super.context.setLiftState(Context.stoppingState);super.context.getLiftState().stop();}}
package com.designPattern.state;public class OpenningState extends LiftState{@Overridepublic void open() { System.out.println("电梯门打开了");}@Overridepublic void close() {super.context.setLiftState(Context.closingState);super.context.getLiftState().close();}@Overridepublic void run() {}@Overridepublic void stop() {}}
package com.designPattern.state;public class RunningState extends LiftState{@Overridepublic void open() {}@Overridepublic void close() {}@Overridepublic void run() {System.out.println("电梯上下跑");}@Overridepublic void stop() {super.context.setLiftState(Context.stoppingState);super.context.getLiftState().stop();}}
package com.designPattern.state;public class StoppingState extends LiftState{@Overridepublic void open() {super.context.setLiftState(Context.openningState);super.context.getLiftState().open();}@Overridepublic void close() {}@Overridepublic void run() {super.context.setLiftState(Context.runningState);super.context.getLiftState().run();}@Overridepublic void stop() {System.out.println("电梯停止了");}}
package com.designPattern.state;public class Context {public static final OpenningState openningState = new OpenningState();public static final ClosingState closingState = new ClosingState();public static final RunningState runningState = new RunningState();public static final StoppingState stoppingState = 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();}}
package com.designPattern.state;public class Client {public static void main(String[] args) {Context context = new Context();context.setLiftState(new ClosingState());context.open();context.close();context.run();context.stop();}}
电梯门打开了电梯门关闭电梯上下跑电梯停止了