标签:相关 list pre 行为型模式 模式 实现 条件 state mic
1) 意图
允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类
2) 结构
其中:
3) 适用性
4) 举例
1 #include <iostream> 2 #include <list> 3 class State; 4 class Context 5 { 6 public: 7 Context(State* state):m_state(state) {} 8 virtual ~Context() 9 { 10 if (m_state) 11 { 12 delete m_state; 13 } 14 } 15 void request(); 16 void changeState(State* state) 17 { 18 if (m_state) delete m_state; 19 m_state = state; 20 } 21 void show(); 22 private: 23 State* m_state; 24 }; 25 class State 26 { 27 public: 28 State(){} 29 virtual ~State() {} 30 virtual void Handle(Context* pContext) = 0; 31 virtual void printState() = 0; 32 }; 33 34 class ConcreateStateA : public State 35 { 36 public: 37 ConcreateStateA() {} 38 virtual ~ConcreateStateA() {} 39 virtual void Handle(Context* pContext); 40 virtual void printState() 41 { 42 std::cout << "state is ConcreateStateA" << std::endl; 43 } 44 }; 45 class ConcreateStateB : public State 46 { 47 public: 48 ConcreateStateB() {} 49 virtual ~ConcreateStateB() {} 50 virtual void Handle(Context* pContext); 51 virtual void printState() 52 { 53 std::cout << "state is ConcreateStateB" << std::endl; 54 } 55 }; 56 void Context::request() 57 { 58 m_state->Handle(this); 59 } 60 void Context::show() 61 { 62 m_state->printState(); 63 } 64 void ConcreateStateA::Handle(Context* pContext) 65 { 66 pContext->changeState(new ConcreateStateB()); 67 } 68 void ConcreateStateB::Handle(Context* pContext) 69 { 70 pContext->changeState(new ConcreateStateA()); 71 } 72 int main() 73 { 74 State* pStateA = new ConcreateStateA(); 75 Context* pContext = new Context(pStateA); 76 pContext->show(); 77 78 pContext->request(); 79 pContext->show(); 80 81 pContext->request(); 82 pContext->show(); 83 84 pContext->request(); 85 pContext->show(); 86 87 delete pContext; 88 system("pause"); 89 }
标签:相关 list pre 行为型模式 模式 实现 条件 state mic
原文地址:https://www.cnblogs.com/ho966/p/12239175.html