状态模式:当一个对象的内在状态改变是允许改变其行为,这个对象看起来像是改变了其类型。状态模式主要解决的是控制一个对象状态转换的条件表达式过于复杂时的情况。 把状态的判断逻辑转移到表示不同状态的一系列类当中,可以把复杂的判断逻辑简单化。
#include <iostream>
using namespace std;
class Work;
class State
{
public:
virtual void WriteProgram(Work* w) = 0;
};
class Work
{
private:
State* currentState;
double hour;
bool taskFinished;
public:
Work( State* state )
{
currentState = state;
taskFinished = false;
}
~Work()
{
delete currentState;
}
void SetHour(int h)
{
hour = h;
}
int GetHour()
{
return hour;
}
void SetTaskFinished(bool task)
{
taskFinished = task;
}
bool GetTaskFinished()
{
return taskFinished;
}
void SetState(State* s)
{
if(currentState != NULL)
delete currentState;
currentState = s;
}
void WriteProgram()
{
currentState->WriteProgram(this);
}
};
class RestState : public State
{
public:
void WriteProgram(Work* w)
{
cout<<"当前时间:"<<w->GetHour()<<"点,下班回家了"<<endl;
}
};
class SleepingState : public State
{
public:
void WriteProgram(Work* w)
{
cout<<"当前时间:"<<w->GetHour()<<"点,睡着了"<<endl;
}
};
class EveningState : public State
{
public:
void WriteProgram(Work* w)
{
if( w->GetTaskFinished() )
{
w->SetState(new RestState());
w->WriteProgram();
}
else
{
if( w->GetHour() < 21 )
{
cout<<"当前时间:"<<w->GetHour()<<"点,加班哦,疲累之极"<<endl;
}
else
{
w->SetState( new SleepingState() );
w->WriteProgram();
}
}
}
};
class AfternoonState : public State
{
public:
void WriteProgram(Work* w)
{
if( w->GetHour() < 17 )
{
cout<<"当前时间:"<<w->GetHour()<<"点, 下午状态还不错,继续努力"<<endl;
}
else
{
w->SetState( new EveningState() );
w->WriteProgram();
}
}
};
class NoonState : public State
{
public:
void WriteProgram( Work* w )
{
if( w->GetHour() < 13 )
{
cout<<"当前时间:"<<w->GetHour()<<"点, 饿了,午饭,午休"<<endl;
}
else
{
w->SetState( new AfternoonState() );
w->WriteProgram();
}
}
};
class ForenoonState : public State
{
public:
void WriteProgram( Work* w )
{
if( w->GetHour() < 12 )
{
cout<<"当前时间:"<<w->GetHour()<<"点,上午工作,精神百倍"<<endl;
}
else
{
w->SetState( new NoonState() );
w->WriteProgram();
}
}
};
int main()
{
Work emergencyProjects( new ForenoonState() );
emergencyProjects.SetHour(9);
emergencyProjects.WriteProgram();
emergencyProjects.SetHour(10);
emergencyProjects.WriteProgram();
emergencyProjects.SetHour(12);
emergencyProjects.WriteProgram();
emergencyProjects.SetHour(13);
emergencyProjects.WriteProgram();
emergencyProjects.SetHour(14);
emergencyProjects.WriteProgram();
emergencyProjects.SetTaskFinished(true);
emergencyProjects.SetHour(17);
emergencyProjects.WriteProgram();
emergencyProjects.SetHour(19);
emergencyProjects.WriteProgram();
emergencyProjects.SetHour(22);
emergencyProjects.WriteProgram();
return 0;
}