C++設計模式之狀態模式
阿新 • • 發佈:2018-07-10
程序 class lse 轉移 tchar pri dot ace RKE
當一個對象的內在狀態改變時允許改變其行為,這個對象看起來像是改變了其類。
狀態模式主要解決的是當控制一個對象狀態轉換的條件表達式過於復雜時的情況。把狀態的判斷邏輯轉移到表示不同狀態的一系列類當中,可以把復雜的判斷邏輯簡化。
將與特點狀態相關的行為局部化,並且將不同狀態的行為分割開來!
1 // State.cpp : 定義控制臺應用程序的入口點。 2 // 3 4 #include "stdafx.h" 5 #include<iostream> 6 #include <string> 7 using namespacestd; 8 class Worker; 9 class State; 10 class StateOne; 11 class StateTwo; 12 13 class Worker 14 { 15 public: 16 Worker(); 17 ~Worker(); 18 void dothing(); 19 int getHour() { 20 return hour; 21 } 22 void setHour(int hour) { 23 this->hour = hour;24 } 25 State* getCurState() { 26 return state; 27 } 28 void setState(State* state) { 29 this->state = state; 30 } 31 private: 32 int hour; 33 State* state; 34 }; 35 36 class State 37 { 38 public: 39 virtual ~State() {} 40 virtualvoid dothing(Worker* worker) = 0; 41 }; 42 43 class StateOne:public State 44 { 45 public: 46 virtual void dothing(Worker* worker); 47 }; 48 49 class StateTwo:public State 50 { 51 public: 52 virtual void dothing(Worker* worker); 53 }; 54 55 void StateOne::dothing(Worker* worker) { 56 int h = worker->getHour(); 57 if (h == 7 || h == 8) { 58 cout << "eat" << endl; 59 } else { 60 delete worker->getCurState(); 61 worker->setState(new StateTwo); 62 worker->getCurState()->dothing(worker); 63 } 64 } 65 66 void StateTwo::dothing(Worker* worker) { 67 int h = worker->getHour(); 68 if (h >= 9) { 69 cout << "work" << endl; 70 } else { 71 delete worker->getCurState(); 72 worker->setState(new StateTwo); 73 worker->getCurState()->dothing(worker); 74 } 75 } 76 77 Worker::Worker() { 78 state = new StateOne; 79 } 80 81 Worker::~Worker() { 82 if (state != NULL){ 83 delete state; 84 state = NULL; 85 } 86 } 87 88 void Worker::dothing() { 89 state->dothing(this); 90 } 91 92 int _tmain(int argc, _TCHAR* argv[]) 93 { 94 cout<<"狀態模式"<<endl; 95 Worker* w = new Worker; 96 w->setHour(7); 97 w->dothing(); 98 99 w->setHour(10); 100 w->dothing(); 101 102 delete w; 103 system("pause"); 104 return 0; 105 }
C++設計模式之狀態模式