当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类当中,可以把复杂的判断逻辑简化。
将与特点状态相关的行为局部化,并且将不同状态的行为分割开来!
1 // State.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include<iostream> 6 #include <string> 7 using namespace std; 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 virtual void 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 }