|
| 1 | +#include <iostream> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +class Sun; |
| 5 | + |
| 6 | +class State { |
| 7 | +public: |
| 8 | + virtual void nextState( Sun* sun ) = 0; |
| 9 | + virtual const char* toString() = 0; |
| 10 | +}; |
| 11 | + |
| 12 | +class Bamdad : public State { |
| 13 | +public: |
| 14 | + virtual void nextState( Sun* sun ); |
| 15 | + virtual const char* toString() { |
| 16 | + return "Bamdad"; |
| 17 | + } |
| 18 | +}; |
| 19 | + |
| 20 | +class Chasht : public State { |
| 21 | +public: |
| 22 | + virtual void nextState( Sun* sun ); |
| 23 | + virtual const char* toString() { |
| 24 | + return "Chasht"; |
| 25 | + } |
| 26 | +}; |
| 27 | + |
| 28 | +class Shamgah : public State { |
| 29 | +public: |
| 30 | + virtual void nextState( Sun* sun ); |
| 31 | + virtual const char* toString() { |
| 32 | + return "Shamgah"; |
| 33 | + } |
| 34 | +}; |
| 35 | + |
| 36 | +class Shabangah : public State { |
| 37 | +public: |
| 38 | + virtual void nextState( Sun* sun ); |
| 39 | + virtual const char* toString() { |
| 40 | + return "Shabangah"; |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +class Sun { |
| 45 | +public: |
| 46 | + Sun( State* state ) |
| 47 | + :_state( state ) { |
| 48 | + } |
| 49 | + |
| 50 | + void afterSixHours() { |
| 51 | + _state->nextState( this ); |
| 52 | + } |
| 53 | + |
| 54 | + void changeState( State* state ) { |
| 55 | + _state = state; |
| 56 | + } |
| 57 | + |
| 58 | + const char* getState() { |
| 59 | + return _state->toString(); |
| 60 | + } |
| 61 | + |
| 62 | +private: |
| 63 | + State* _state; |
| 64 | +}; |
| 65 | + |
| 66 | +void Bamdad::nextState( Sun* sun ) { |
| 67 | + sun->changeState( new Chasht() ); |
| 68 | +} |
| 69 | + |
| 70 | +void Chasht::nextState( Sun* sun ) { |
| 71 | + sun->changeState( new Shamgah() ); |
| 72 | +} |
| 73 | + |
| 74 | +void Shamgah::nextState( Sun* sun ) { |
| 75 | + sun->changeState( new Shabangah() ); |
| 76 | +} |
| 77 | + |
| 78 | +void Shabangah::nextState( Sun* sun ) { |
| 79 | + sun->changeState( new Bamdad() ); |
| 80 | +} |
| 81 | + |
| 82 | +int main() { |
| 83 | + |
| 84 | + Sun* sun = new Sun( new Bamdad() ); |
| 85 | + sun->afterSixHours(); |
| 86 | + cout << sun->getState() << endl; |
| 87 | + |
| 88 | + sun->afterSixHours(); |
| 89 | + cout << sun->getState() << endl; |
| 90 | + |
| 91 | + sun->afterSixHours(); |
| 92 | + cout << sun->getState() << endl; |
| 93 | + |
| 94 | + sun->afterSixHours(); |
| 95 | + cout << sun->getState() << endl; |
| 96 | + |
| 97 | + sun->afterSixHours(); |
| 98 | + cout << sun->getState() << endl; |
| 99 | + |
| 100 | + return 0; |
| 101 | +} |
0 commit comments