java学习

java学习

 

设计模式之状态模式

现在写一个用状态模式实现的根据上班时间状态变化而行为变化的小程序,当时间<12上午上班时间,
<13午休时间,<17下午上班时间,<21加班时间,根据时间不同,条用的类方法不同。
状态模式适用于当对象的状态改变时,行为也改变,就可以使用状态模式
状态接口:
public interface State {
void writeProgram(Work work);
}
不同的实现类:

public class AfterNoonState implements State {

 @Override
 public void writeProgram(Work work) {
  if(work.getHour()<17){
   System.out.println("工作");
  }else {
   work.setCurrent(new EveningState());
   work.writeProgram();
  }

 }

}


public class EveningState implements State {

 @Override
 public void writeProgram(Work work) {
 if(work.isFinish()){
  work.setCurrent(new RestState());
  work.writeProgram();
 }else {
  if(work.getHour()<21){
   System.out.println("加班");
  }else {
   work.setCurrent(new SleepState());
   work.writeProgram();
  }
 }

 }

}


public class ForenoonState implements State {

 @Override
 public void writeProgram(Work work) {
 if(work.getHour()<12){
  System.out.println("工作时间");
 }else {
 work.setCurrent(new NoonState()); 
 work.writeProgram();
 }
  
 }

}


public class NoonState implements State {

 @Override
 public void writeProgram(Work work) {
  if(work.getHour()<13){
   System.out.println("午睡");
  }else {
   work.setCurrent(new AfterNoonState());
   work.writeProgram();
  }

 }

}


public class RestState implements State {

 @Override
 public void writeProgram(Work work) {
  System.out.println("回家");

 }

}


public class SleepState implements State {

 @Override
 public void writeProgram(Work work) {
  System.out.println("睡觉");

 }

}


调用状态的类:

public class Work {
private State current;

 public Work(double hour,boolean finish){
 current = new ForenoonState();
 this.hour = hour;
 this.finish = finish;
}
private double hour;
public double getHour() {
 return hour;
}

public State getCurrent() {
 return current;
}
public void setCurrent(State current) {
 this.current = current;
}
private boolean finish;
public boolean isFinish() {
 return finish;
}

public void writeProgram(){
 current.writeProgram(this);
}
}


测试类:
public class Test {
public static void main(String[] args) {
 Work work = new Work(20, true);
 work.writeProgram();
}
}

posted on 2013-05-06 14:24 杨军威 阅读(92) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜