当前位置:   article > 正文

大话设计模式-状态模式_.net大话状态模式

.net大话状态模式

场景:工作状态随时间的变化而变化

状态模式,当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类

要点:工作由状态聚合而成;将状态的变化影响抽象出来,且状态变化依赖工作类本身;抽象状态类代理了工作类

1. 抽象状态,早晨状态、中午状态、下午状态、下班状态

  1. package com.hj.designPattern.behavior.state;
  2. public abstract class State {
  3. public abstract void writeProgram(Work work);
  4. }
  5. package com.hj.designPattern.behavior.state;
  6. public class MorningState extends State {
  7. @Override
  8. public void writeProgram(Work work) {
  9. if(work.getHour()>9 && work.getHour()<=12){
  10. System.out.println("精神抖擞,活力满满");
  11. } else {
  12. work.setNextState(new NoonState());
  13. work.writeProgram();
  14. }
  15. }
  16. }
  17. package com.hj.designPattern.behavior.state;
  18. public class NoonState extends State {
  19. @Override
  20. public void writeProgram(Work work) {
  21. if(work.getHour()>12 && work.getHour()<=15){
  22. System.out.println("吃饱喝足,有点犯困");
  23. } else {
  24. work.setNextState(new AfternoonState());
  25. work.writeProgram();
  26. }
  27. }
  28. }
  29. package com.hj.designPattern.behavior.state;
  30. public class AfternoonState extends State {
  31. @Override
  32. public void writeProgram(Work work) {
  33. if(work.getHour()>15 && work.getHour()<=18){
  34. System.out.println("快下班了,努力工作");
  35. } else {
  36. work.setNextState(new FinishState());
  37. work.writeProgram();
  38. }
  39. }
  40. }
  41. package com.hj.designPattern.behavior.state;
  42. public class FinishState extends State {
  43. @Override
  44. public void writeProgram(Work work) {
  45. if(work.getHour()>18 && work.getHour()<=24 || work.getHour()>0 && work.getHour()<=9){
  46. System.out.println("下班了,休息休息,谁也不要打扰我");
  47. } else {
  48. work.setNextState(new MorningState());
  49. work.writeProgram();
  50. }
  51. }
  52. }

2. 工作类

  1. package com.hj.designPattern.behavior.state;
  2. public class Work {
  3. private State state;
  4. private int hour;
  5. Work(){
  6. state = new MorningState();
  7. }
  8. public void writeProgram(){
  9. state.writeProgram(this);
  10. }
  11. public void setNextState(State state){
  12. this.state = state;
  13. }
  14. public int getHour() {
  15. return hour;
  16. }
  17. public void setHour(int hour) {
  18. this.hour = hour;
  19. }
  20. }

 3. 测试类

  1. package com.hj.designPattern.behavior.state;
  2. public class StateTest {
  3. public static void main(String[] args) {
  4. Work work = new Work();
  5. work.setHour(8);
  6. work.writeProgram();
  7. work.setHour(10);
  8. work.writeProgram();
  9. work.setHour(14);
  10. work.writeProgram();
  11. work.setHour(17);
  12. work.writeProgram();
  13. work.setHour(23);
  14. work.writeProgram();
  15. }
  16. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/421442
推荐阅读
相关标签
  

闽ICP备14008679号