概念:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
核心:主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中。

状态模式结构图

image.png

image.png

java代码:

  1. public class StateTest {
  2. public static void main(String[] args) {
  3. Work work = new Work(new NoonState());
  4. work.Hour = 10;
  5. work.WriteProgram();
  6. work.Hour = 17;
  7. work.WriteProgram();
  8. work.Hour = 22;
  9. work.WriteProgram();
  10. }
  11. }
  12. public class Work {
  13. int Hour;
  14. boolean finfish;
  15. State state;
  16. public Work(State state) {
  17. this.state = state;
  18. }
  19. public void WriteProgram(){
  20. state.writeProgram(this);
  21. }
  22. }
  23. public abstract class State {
  24. public abstract void writeProgram(Work w);
  25. }
  26. public class ForenoonState extends State {
  27. @Override
  28. public void writeProgram(Work w) {
  29. if (w.Hour < 12){
  30. System.out.println("当前时间: " + w.Hour + ",精神百倍, 努力工作");
  31. }else{
  32. w.state = new NoonState();
  33. w.state.writeProgram(w);
  34. }
  35. }
  36. }
  37. public class NoonState extends State{
  38. @Override
  39. public void writeProgram(Work w) {
  40. if (w.Hour < 20){
  41. System.out.println("下午时间"+ w.Hour +"有点犯困");
  42. }else{
  43. w.state = new AfternoonState();
  44. w.state.writeProgram(w);
  45. }
  46. }
  47. }
  48. public class AfternoonState extends State {
  49. @Override
  50. public void writeProgram(Work w) {
  51. if (w.Hour < 24){
  52. System.out.println("晚上时间"+ w.Hour +"加班严重");
  53. }else{
  54. System.out.println("等着猝死");
  55. }
  56. }
  57. }