2.一个操作中含有庞大的多分支结构,并且这些分支决定于对象的状态。
类图结构:
这样的话让程序更加面向对象
状态模式的好处是将与特定状态相关的行为局部化,并且将不同的状态行为分割开来。
目的就是消除庞大的分支语句,状态模式通过把各种状态转移逻辑分布到state的子类之间,
来减少相互间的依赖。
什么时候使用?
当一个对象的行为取决于它的状态,并且它必须在运行时根据状态改变它的行为时,就可以
考虑状态模式。
参考代码如下:
#ifndef _STATE_H_
#define _STATE_H_
#include <iostream>
#include <string>
using namespace std;
class Work;
class State{
public:
virtual void writeProgram(Work* work) = 0;
};
//12 before
class ForenoonState : public State{
public:
void writeProgram(Work* work);
};
//12 ~ 13 middle
class MoonState:public State{
public:
void writeProgram(Work* work);
};
//12 ~ 13 middle
class AfterMoonState:public State{
public:
void writeProgram(Work* work);
};
//晚间
class EveningState:public State{
public:
void writeProgram(Work* work);
};
//休息
class RestState:public State{
public:
void writeProgram(Work* work);
};
//睡觉
class SleepingState:public State{
public:
void writeProgram(Work* work);
};
class Work{
private:
State* m_current;
int m_hour;
bool m_finish;
public:
Work(void):m_current(NULL),m_finish(false),m_hour(0){
m_current = new ForenoonState();
}
int getHour(void){
return m_hour;
}
void setHour(const int hour){
m_hour = hour;
}
bool getIsFinished(void){
return m_finish;
}
void setFinishFlag(const bool bFinished){
m_finish = bFinished;
}
void setState(State* state){
m_current = state;
}
void writeProgram(){
m_current->writeProgram(this);
}
};
void ForenoonState::writeProgram(Work* work){
if(work->getHour()<12){
cout<<"当前时间:"<<work->getHour()<<"点 上午工作,精神百倍"<<endl;
}else{
work->setState(new MoonState());
work->writeProgram();
}
}
void MoonState::writeProgram(Work* work){
if(work->getHour()<13){
cout<<"当前时间:"<<work->getHour()<<"点 午休,得去吃饭了!"<<endl;
}else{
work->setState(new AfterMoonState());
//work->writeProgram();
}
}
void AfterMoonState::writeProgram(Work* work){
if(work->getHour()<17){
cout<<"当前时间:"<<work->getHour()<<"点 下午状态还可以,继续努力!"<<endl;
}else{
work->setState(new EveningState());
work->writeProgram();
}
}
void EveningState::writeProgram(Work* work){
if(work->getIsFinished()){
work->setState(new RestState());
work->writeProgram();
}else{
if(work->getHour()<21){
cout<<"当前时间:"<<work->getHour()<<"点 加班啊,疲惫之极!"<<endl;
}else{
work->setState(new SleepingState());
work->writeProgram();
}
}
}
void RestState::writeProgram(Work* work){
cout<<"当前时间:"<<work->getHour()<<"点 下班回家了!"<<endl;
}
void SleepingState::writeProgram(Work* work){
cout<<"当前时间:"<<work->getHour()<<"点 不行了睡着了!"<<endl;
}
#endif
void main(){
Work* work = new Work();
work->setHour(9);
work->writeProgram();
work->setHour(10);
work->writeProgram();
work->setHour(12);
work->writeProgram();
work->setHour(13);
work->writeProgram();
work->setHour(14);
work->writeProgram();
work->setHour(17);
work->writeProgram();
work->setFinishFlag(false);
work->writeProgram();
work->setHour(19);
work->writeProgram();
work->setHour(21);
work->writeProgram();
}
对于状态频繁变更需要考虑状态模式。