Mode definition
The State mode allows an object to change its behavior when its internal state changes. The object seems to have modified its class.
Mode structure:
Context: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + u7e + s7ao0uW/zbunuNDQy8iktcS907/large + large/large + CjxoMT6 + large/large + large "http://www.2cto.com/uploadfile/Collfiles/20140613/20140613092010195.jpg" alt = "\">
Programming implementation and execution results:
# Include
Using namespace std; class Worker; // class pre-declaration // status class State {public: virtual void doing (Worker * w ){}}; // working status class WorkingState: public State {public: void doing (Worker * worker) ;}; // rest status class SleepingState: public State {public: void doing (Worker * worker) ;}; // other States class OtherState: public State {public: void doing (Worker * worker );}; // Worker class Worker {public: Worker () {state = new WorkingState ();} void setState (St Ate * stat) {state = stat;} double getHour () {return hour;} void setHour (double hou) {hour = hou;} void requestDoing () {state-> doing (this) ;}private: State * state; double hour ;}; // void WorkingState: doing (Worker * worker) {if (worker-> getHour ()> 8 & worker-> getHour () <16) cout <"WorkingState! "<Endl; else {worker-> setState (new OtherState (); worker-> requestDoing () ;}} void SleepingState: doing (Worker * worker) {if (worker-> getHour ()> = 21 | worker-> getHour () <5) cout <"SleepingState! "<Endl; else {worker-> setState (new OtherState (); worker-> requestDoing () ;}} void OtherState: doing (Worker * worker) {if (worker-> getHour ()> = 5 & worker-> getHour () <8) | (worker-> getHour ()> = 16 & worker-> getHour () <21) cout <"SleepingState! "<Endl; else if (worker-> getHour ()> = 21 | worker-> getHour () <5) {worker-> setState (new SleepingState ()); worker-> requestDoing ();} else {worker-> setState (new WorkingState (); worker-> requestDoing () ;}// client code int main () {Worker * pWorker = new Worker (); pWorker-> setHour (24); cout <"time 24" <endl; pWorker-> requestDoing (); pWorker-> setHour (11.5); cout <"time 11.5" <endl; pWorker-> requestDoing (); pWorker-> setHour (19 ); cout <"time 19" <endl; pWorker-> requestDoing (); delete pWorker; return 0 ;}
Execution result:
Time24
SleepingState!
Time11.5
WorkingState!
Time19
SleepingState!
Press any key to continue...