fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Machine
  5. {
  6. class State *current;
  7. class State *nextstate;
  8. void check_transition();
  9. public:
  10. Machine();
  11. void setCurrent(State *s)
  12. {
  13. nextstate = s;
  14. //current = s;
  15. }
  16. void set_on();
  17. void set_off();
  18. };
  19.  
  20. class State
  21. {
  22. public:
  23. virtual void set_on(Machine *m)
  24. {
  25. cout << " already ON\n";
  26. }
  27. virtual void set_off(Machine *m)
  28. {
  29. cout << " already OFF\n";
  30. }
  31. virtual ~State(){}
  32. };
  33.  
  34. void Machine::check_transition() {
  35. if (nextstate) {
  36. swap (current, nextstate);
  37. delete nextstate; // this contains the former current
  38. nextstate = nullptr;
  39. }
  40. }
  41.  
  42. void Machine::set_on()
  43. {
  44. current->set_on(this);
  45. check_transition();
  46. }
  47.  
  48. void Machine::set_off()
  49. {
  50. current->set_off(this);
  51. check_transition();
  52. }
  53.  
  54. class ON: public State
  55. {
  56. public:
  57. ON()
  58. {
  59. cout << " ON-ctor ";
  60. };
  61. ~ON()
  62. {
  63. cout << " dtor-ON\n";
  64. };
  65. void set_off(Machine *m);
  66. };
  67.  
  68. class OFF: public State
  69. {
  70. public:
  71. OFF()
  72. {
  73. cout << " OFF-ctor ";
  74. };
  75. ~OFF()
  76. {
  77. cout << " dtor-OFF\n";
  78. };
  79. void set_on(Machine *m)
  80. {
  81. cout << " going from OFF to ON";
  82. m->setCurrent(new ON());
  83. }
  84. };
  85.  
  86. void ON::set_off(Machine *m)
  87. {
  88. cout << " going from ON to OFF";
  89. m->setCurrent(new OFF());
  90. }
  91.  
  92. Machine::Machine()
  93. {
  94. nextstate = nullptr;
  95. current = new OFF();
  96. cout << '\n';
  97. }
  98.  
  99. int main()
  100. {
  101. void(Machine:: *ptrs[])() =
  102. {
  103. &Machine::set_off, &Machine::set_on
  104. };
  105. Machine fsm;
  106. int num;
  107. cout << "Enter 0/1: ";
  108.  
  109. while (cin >> num)
  110. {
  111.  
  112. (fsm.*ptrs[num])();
  113. cout << "Enter 0/1: ";
  114. }
  115. }
Success #stdin #stdout 0s 3236KB
stdin
1 1 0
stdout
   OFF-ctor 
Enter 0/1:    going from OFF to ON   ON-ctor    dtor-OFF
Enter 0/1:    already ON
Enter 0/1:    going from ON to OFF   OFF-ctor    dtor-ON
Enter 0/1: