publicabstractclassLiftState{protectedLiftContextliftContext;publicvoidsetLiftContext(LiftContextliftContext){this.liftContext=liftContext;}publicabstractvoidopenDoor();publicabstractvoidcloseDoor();publicabstractvoidrun();publicabstractvoidstop();}publicclassClosingStateextendsLiftState{@OverridepublicvoidopenDoor(){super.liftContext.setLiftState(LiftContext.OPENING_STATE);super.liftContext.openDoor();}@OverridepublicvoidcloseDoor(){System.out.println("Close door");}@Overridepublicvoidrun(){super.liftContext.setLiftState(LiftContext.RUNNING_STATE);super.liftContext.run();}@Overridepublicvoidstop(){super.liftContext.setLiftState(LiftContext.STOPPING_AND_CLOSE_STATE);super.liftContext.stop();}}publicclassOpeningStateextendsLiftState{@OverridepublicvoidopenDoor(){System.out.println("open the door");}@OverridepublicvoidcloseDoor(){super.liftContext.setLiftState(LiftContext.CLOSING_STATE);super.liftContext.closeDoor();}@Overridepublicvoidrun(){System.out.println("(Opening, I can not run)");// can't run now}@Overridepublicvoidstop(){// already stopped, do nothing. But door is open}}publicclassRunningStateextendsLiftState{@OverridepublicvoidopenDoor(){System.out.println("(Running, can't open door)");}@OverridepublicvoidcloseDoor(){System.out.println("(Running, the door is already closed)");}@Overridepublicvoidrun(){System.out.println("Running up or down...");}@Overridepublicvoidstop(){super.liftContext.setLiftState(LiftContext.STOPPING_AND_CLOSE_STATE);super.liftContext.stop();}}publicclassStoppingAndCloseStateextendsLiftState{@OverridepublicvoidopenDoor(){super.liftContext.setLiftState(LiftContext.STOPPING_AND_OPEN_STATE);super.liftContext.openDoor();}@OverridepublicvoidcloseDoor(){System.out.println("close the door");}@Overridepublicvoidrun(){super.liftContext.setLiftState(LiftContext.RUNNING_STATE);super.liftContext.run();}@Overridepublicvoidstop(){System.out.println("Stop and door is close");}}publicclassStoppingAndOpenStateextendsLiftState{@OverridepublicvoidopenDoor(){System.out.println("open the door");}@OverridepublicvoidcloseDoor(){super.liftContext.setLiftState(LiftContext.STOPPING_AND_CLOSE_STATE);super.liftContext.closeDoor();}@Overridepublicvoidrun(){System.out.println("(can't run, please close the door first!)");}@Overridepublicvoidstop(){System.out.println("(already open)");}}
LiftContextliftContext=newLiftContext();liftContext.setLiftState(LiftContext.STOPPING_AND_CLOSE_STATE);liftContext.closeDoor();liftContext.openDoor();// somebody goes inliftContext.closeDoor();liftContext.run();liftContext.stop();liftContext.openDoor();// somebody leavesliftContext.run();liftContext.stop();liftContext.closeDoor();liftContext.run();liftContext.openDoor();/* 控制台输出close the dooropen the doorclose the doorRunning up or down...Stop and door is closeopen the door(can't run, please close the door first!)(already open)close the doorRunning up or down...(Running, can't open door)*/