当前位置:   article > 正文

软件设计模式 --状态模式_软件设计中多种状态变量

软件设计中多种状态变量

//P: 抽象状态类,实现具体类,根据需要生成具体类对象赋值给抽象类变量 

强调的是对象,不同情况下,自生状态的改变

2021.08.3: 强调状态的变化, 所以把状态 抽象出来。

  1. #include <stdio.h>
  2. #include <iostream>
  3. using namespace std;
  4. class War;
  5. class State
  6. {
  7. public:
  8. virtual void Prophase() {}
  9. virtual void Metaphase() {}
  10. virtual void Anaphase() {}
  11. virtual void End() {}
  12. virtual void CurrentState(War *war) {}
  13. };
  14. //战争
  15. class War
  16. {
  17. private:
  18. State *m_state; //目前状态
  19. int m_days; //战争持续时间
  20. public:
  21. War(State *state): m_state(state), m_days(0) {}
  22. ~War() { delete m_state; }
  23. int GetDays() { return m_days; }
  24. void SetDays(int days) { m_days = days; }
  25. void SetState(State *state) { delete m_state; m_state = state; }
  26. void GetState() { m_state->CurrentState(this); }
  27. };
  28. class EndState: public State
  29. {
  30. public:
  31. void End(War *war) //结束阶段的具体行为
  32. {
  33. cout<<"战争结束"<<endl;
  34. }
  35. void CurrentState(War *war) { End(war); }
  36. };
  37. //后期
  38. class AnaphaseState: public State
  39. {
  40. public:
  41. void Anaphase(War *war) //后期的具体行为
  42. {
  43. if(war->GetDays() < 30)
  44. cout<<"第"<<war->GetDays()<<"天:战争后期,双方拼死一搏"<<endl;
  45. else
  46. {
  47. war->SetState(new EndState());
  48. war->GetState();
  49. }
  50. }
  51. void CurrentState(War *war) { Anaphase(war); }
  52. };
  53. //中期
  54. class MetaphaseState: public State
  55. {
  56. public:
  57. void Metaphase(War *war) //中期的具体行为
  58. {
  59. if(war->GetDays() < 20)
  60. cout<<"第"<<war->GetDays()<<"天:战争中期,进入相持阶段,双发各有损耗"<<endl;
  61. else
  62. {
  63. war->SetState(new AnaphaseState());
  64. war->GetState();
  65. }
  66. }
  67. void CurrentState(War *war) { Metaphase(war); }
  68. };
  69. //前期
  70. class ProphaseState: public State
  71. {
  72. public:
  73. void Prophase(War *war) //前期的具体行为
  74. {
  75. if(war->GetDays() < 10)
  76. cout<<"第"<<war->GetDays()<<"天:战争初期,双方你来我往,互相试探对方"<<endl;
  77. else
  78. {
  79. war->SetState(new MetaphaseState());
  80. war->GetState();
  81. }
  82. }
  83. void CurrentState(War *war) { Prophase(war); }
  84. };
  85. int main()
  86. {
  87. War *m_war = new War(new ProphaseState);
  88. for (int i=0 ;i< 40; i=i+10)
  89. {
  90. m_war->SetDays(i);
  91. m_war->GetState();
  92. }
  93. delete m_war;
  94. getchar();
  95. return 0;
  96. }


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

闽ICP备14008679号