状态模式
状态模式,当一个对象的内在状态改变时同意改变其行为,这个对象看起来像是改变了其类。
状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的推断逻辑转移到表示不同状态的一系列类其中,能够把复杂的推断逻辑简化。
适用场景:
- 一个对象的行为取决于他的状态,而且它必须在执行时刻依据状态改变他的行为。
- 一个操作中含有庞大的多分支结构,而且这些分支决定于对象的状态。
代码实例结构图:
代码:
//Status.h
#include "stdafx.h" #include <iostream> using namespace std; class Work; class State { public: virtual ~State(){} virtual void WritePrograme(Work* work) = 0; }; class Work { private: State* Current; double Hour; bool finish = false; public: ~Work() { if (Current != NULL) delete Current; } double GetHour(){ return Hour; } void SetHour(double hour){ Hour = hour; } bool TaskFinished(){ return finish; } void SetFinish(bool f){ finish = f; } void SetState(State* s){ Current = s; } void WritePrograme() { Current->WritePrograme(this); } }; class SleepingState :public State { public: virtual void WritePrograme(Work* work) { cout << "睡觉时间" << endl; } }; class AfternoonState :public State { public: virtual void WritePrograme(Work* work) { if (work->GetHour() < 18) { cout << "下午时间" << endl; } else { work->SetState(new SleepingState()); work->WritePrograme(); } } }; class ForenoonState :public State { public: virtual void WritePrograme(Work* work) { if (work->GetHour() < 12) { cout << "上午时间" << endl; } else { work->SetState(new AfternoonState()); work->WritePrograme(); } } };// StatusPattern.cpp
// StatusPattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Status.h" int _tmain(int argc, _TCHAR* argv[]) { Work* work = new Work(); work->SetState(new ForenoonState()); work->SetHour(10); work->WritePrograme(); work->SetHour(20); work->WritePrograme(); getchar(); return 0; }