首先写一个State类
package State;
import Work.Work;
public abstract class State {
public abstract void WriteProgram(Work w);
}
再写六个状态用来继承
package State;
import Work.Work;
public class ForenoonState extends State{
@Override
public void WriteProgram(Work w) {
// TODO Auto-generated method stub
if(w.getHour()<12)
{
System.out.println("当前时间:"+w.getHour()+"上午工作,精神百倍");
}
else
{
w.setState(new NoonState());
w.WriteProgram();
}
}
}
package State;
import Work.Work;
public class NoonState extends State{
@Override
public void WriteProgram(Work w) {
// TODO Auto-generated method stub
if(w.getHour()<13)
{
System.out.println("当前时间:"+w.getHour()+"饿了,午饭;犯困,午休");
}
else
{
w.setState(new AfternonState());
w.WriteProgram();
}
}
}
package State;
import Work.Work;
public class AfternonState extends State{
@Override
public void WriteProgram(Work w) {
// TODO Auto-generated method stub
if(w.getHour()<17)
{
System.out.println("当前时间:"+w.getHour()+"下午状态还不错,继续努力");
}
else
{
w.setState(new EveningState());
w.WriteProgram();
}
}
}
package State;
import Work.Work;
public class EveningState extends State
{
@Override
public void WriteProgram(Work w) {
// TODO Auto-generated method stub
if(w.isFinish())
{
w.setState(new RestState());
w.WriteProgram();
}
else
{
if(w.getHour()<21)
{
System.out.println("当前时间:"+w.getHour()+"加班o,疲惫之极");
}
else
{
w.setState(new SleepingState());
}
}
}
}
package State;
import Work.Work;
public class RestState extends State{
@Override
public void WriteProgram(Work w) {
// TODO Auto-generated method stub
System.out.println("当前时间:"+w.getHour()+"下班回家了");
}
}
package State;
import Work.Work;
public class SleepingState extends State{
@Override
public void WriteProgram(Work w) {
// TODO Auto-generated method stub
System.out.println("当前时间:"+w.getHour()+"不行了,睡着了");
}
}
写一个work
package Work;
import State.ForenoonState;
import State.State;
public class Work {
private int hour;
private boolean finish = false;
private State state;
public Work()
{
state = new ForenoonState();
}
public void WriteProgram()
{
state.WriteProgram(this);
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public boolean isFinish() {
return finish;
}
public void setFinish(boolean finish) {
this.finish = finish;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
最后写测试类
import Work.Work;
public class Program {
public static void main(String[] args) {
// TODO Auto-generated method stub
Work emergencyProj = new Work();
emergencyProj.setHour(9);
emergencyProj.WriteProgram();
emergencyProj.setHour(10);
emergencyProj.WriteProgram();
emergencyProj.setHour(12);
emergencyProj.WriteProgram();
emergencyProj.setHour(13);
emergencyProj.WriteProgram();
emergencyProj.setHour(14);
emergencyProj.WriteProgram();
emergencyProj.setHour(17);
emergencyProj.setFinish(false);
emergencyProj.WriteProgram();
emergencyProj.setHour(19);
emergencyProj.WriteProgram();
emergencyProj.setHour(22);
emergencyProj.WriteProgram();
}
}