标签:c++ 设计模式
状态模式,当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。#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; }
标签:c++ 设计模式
原文地址:http://blog.csdn.net/wwwdongzi/article/details/26880131