package org.ustc.statemode; public class Work { private State state; private boolean isFinished ; public Work() { state = new MoningState(); setFinished(false); } public State getState() { return state; } public void setState(State state) { this.state = state; } public int getHour() { return hour; } public void setHour(int hour) { this.hour = hour; } private int hour; public void writeProgram(){ state.writeProgram(this); } public void setFinished(boolean isFinished) { this.isFinished = isFinished; } public boolean isFinished() { return isFinished; } }
package org.ustc.statemode; public interface State { public void writeProgram(Work w); }
package org.ustc.statemode; public class MoningState implements State { @Override public void writeProgram(Work w) { // TODO Auto-generated method stub if(w.getHour()<12) System.out.println("精力充沛,time:"+w.getHour()); else{ w.setState(new AfternoonState()); w.writeProgram(); } } }
package org.ustc.statemode; public class AfternoonState implements State { @Override public void writeProgram(Work w) { // TODO Auto-generated method stub if(w.getHour()<17) System.out.println("下午犯困"); else{ w.setState(new EveningState()); w.writeProgram(); } } }
package org.ustc.statemode; public class EveningState implements State { @Override public void writeProgram(Work w) { // TODO Auto-generated method stub if(w.isFinished()==true){ w.setState(new RestState()); w.writeProgram(); }else{ if(w.getHour()<20) System.out.println("好累"); else{ w.setState(new SleepState()); w.writeProgram(); } } } }
package org.ustc.statemode; public class RestState implements State { @Override public void writeProgram(Work w) { // TODO Auto-generated method stub System.out.println("收工 下班咯"); } }
package org.ustc.statemode; public class SleepState implements State { @Override public void writeProgram(Work w) { // TODO Auto-generated method stub System.out.println("不行了睡着了"+w.getHour()); } }
package org.ustc.statemode; public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Work work = new Work(); //work.setHour(20); //work.setHour(9); // work.setHour(14); work.setFinished(true); work.setHour(20); work.writeProgram(); } }