// StatePattern.cpp : 定义控制台应用程序的入口点。
//通过此例程了解设计模式里的“状态模式”
//状态模式提供一个状态接口,如果要增加其他状态,只要从这个状态接口派生即可
//下面利用本人这段时间一天内的学习情况来解释状态模式
//假设我们大四可以自由活动(可以逃课)
//则一天内,上午(8--11):工作(算法练习,c++语法练习)
//中午(11--2:00):午餐时间,午休时间
//下午(2:00--5:00):工作,练习设计模式
//傍晚时间(5--6:00):晚餐时间
//晚上(6--11:00):写代码,看新闻,电视剧
//(11:00--):睡觉时间,累了
#include "stdafx.h"
#include <process.h>
#include <iostream>
using namespace std;
class CWork;
class CState
{
public:
virtual void Work(CWork *w) = 0;
};
//工作类
class CWork
{
private:
CState *m_CurState;//当前状态
double m_CurHour;
public:
CWork()
{
}
void SetTime(double hour)
{
this->m_CurHour = hour;
}
double GetTime()
{
return this->m_CurHour;
}
//设置状态
void SetState(CState *s)
{
m_CurState = s;
}
void Work()
{
m_CurState->Work(this);
}
};
//晚上时间
class CEveningState : public CState
{
public:
void Work(CWork *w)
{
if (w->GetTime()<23)
{
cout<<"当前时间是:"<<w->GetTime()<<" 正在码代码或者看电视剧"<<endl;
}
else
{
cout<<"当前时间是:"<<w->GetTime()<<" 正在睡觉"<<endl;
}
}
};
//傍晚时间
class CTowardEveningState:public CState
{
public:
void Work(CWork *w)
{
if (w->GetTime()<18)
{
cout<<"当前时间是:"<<w->GetTime()<<" 傍晚时间,正在进餐"<<endl;
}
else
{
w->SetState(new CEveningState());
w->Work();
}
}
};
//下午时间
class CAfterNoonState : public CState
{
public:
void Work(CWork *w)
{
if (w->GetTime()<15)
{
cout<<"当前时间是:"<<w->GetTime()<<" 下午时间,正在练习设计模式"<<endl;
}
else
{
w->SetState(new CTowardEveningState());
w->Work();
}
}
};
//中午时间
class CNoonState:public CState
{
public:
void Work(CWork *w)
{
if (w->GetTime()<14)
{
cout<<"当前时间是:"<<w->GetTime()<<" 中午时间,正在进餐或者午睡"<<endl;
}
else
{
w->SetState(new CAfterNoonState());
w->Work();
}
}
};
//上午工作
class CForeNoonState : public CState
{
public:
void Work(CWork *w)
{
if (w->GetTime()<11)
{
cout<<"当前时间是:"<<w->GetTime()<<" 上午时间,正在练习算法和c++语法"<<endl;
}
else
{
w->SetState(new CNoonState());
w->Work();
}
}
};
void main()
{
cout<<"-------------状态模式测试案例-----------------"<<endl<<endl;
CWork *StartWork = new CWork();
StartWork->SetState(new CForeNoonState());
StartWork->SetTime(9);
StartWork->Work();
StartWork->SetTime(12);
StartWork->Work();
StartWork->SetTime(14);
StartWork->Work();
StartWork->SetTime(15);
StartWork->Work();
StartWork->SetTime(19);
StartWork->Work();
StartWork->SetTime(24);
StartWork->Work();
system("pause");
}