目标:当一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,可考虑使用状态模式。
示例代码:
#include
using namespace std;
class Work;
class ForenoonState;
class NoonState;
class State
{
public:
virtual void WriteProgram(Work* w)=0;
};
class Work
{
private:
State* current;
public:
double hour;
public:
Work();
void SetState(State* temp)
{
current = temp;
}
void WriteProgram()
{
current->WriteProgram(this);
}
};
class NoonState : public State
{
public:
virtual void WriteProgram(Work* w)
{
cout << "execute" << endl;
if((w->hour) < 13)
{
cout << "还不错了" << endl;
}
else
{
cout << "不行了,还是睡觉吧" << endl;
}
}
};
class ForenoonState : public State
{
public:
virtual void WriteProgram(Work* w)
{
if((w->hour) < 12)
{
cout << "现在的精神无敌好" << endl;
}
else
{
w->SetState(new NoonState());
w->WriteProgram(); //
}
}
};
Work::Work()
{
current = new ForenoonState();
}
//客户端
int main()
{
Work* mywork = new Work();
mywork->hour = 9;
mywork->WriteProgram();
mywork->hour = 14;
mywork->WriteProgram();
return 0;
}
阅读(819) | 评论(0) | 转发(0) |