状态模式包含如下角色:
- Context: 环境类
- State: 抽象状态类
- ConcreteState: 具体状态类
2)适用场景:
a)状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的判 断逻辑简单化。(简单来说,就是把各种if else 转变成了一个个的具体状态,原来if else 每种情况下的操作现在转换到了某个具体状态中)
b)当一个对象行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为时,就可以考虑使用状态模式了。
State.h
#ifndef STATE
#define STATE
extern class Work; class State
{
public:
State(){};
virtual void writeProgram(Work* w){};
}; class ForenoonState :public State
{
public:
void writeProgram(Work* w);
}; class NoonState :public State
{
public:
void writeProgram(Work* w);
}; class AfternoonState :public State
{
public:
void writeProgram(Work* w);
}; class RestState :public State
{
public:
void writeProgram(Work* w);
}; #endif
state.cpp
#include <iostream>
#include "State.h"
#include "Work.h" using namespace std; void ForenoonState :: writeProgram(Work* w)
{
if (w->getHour() < )
cout << "当前时间:" << w->getHour() << "点 " << "ForenoonState,精神百倍" << endl;
else
{
w->setState(new NoonState);//下一个状态
w->writeProgram();
}
} void NoonState:: writeProgram(Work* w)
{
if (w->getHour() < )
cout << "当前时间:" << w->getHour() << "点 " << "NoonState,精神百倍" << endl;
else
{
w->setState(new AfternoonState);//下一个状态
w->writeProgram();
}
} void AfternoonState :: writeProgram(Work* w)
{ if (w->getHour() < )
cout << "当前时间:" << w->getHour() << "点 " << "AfternoonState,精神百倍" << endl;
else
{
w->setState(new RestState);//下一个状态
w->writeProgram();
} } void RestState:: writeProgram(Work* w)
{
cout << "当前时间:" << w->getHour() << "点 " << "RestState,精神百倍" << endl; }
work.h
#ifndef WORK
#define WORK #include "State.h"
class Work
{
private:
State* currnetState;
double Hour;
bool finish;
public:
Work();
~Work();
double getHour();
void setHour(double h); bool getFinish();
void setFinish(bool f); void setState(State* s);
void writeProgram();
}; #endif
work.cpp
#include "Work.h" Work::Work(){
currnetState = new ForenoonState;
Hour = ;
finish = false;
}
Work::~Work()
{
if (currnetState != )
delete currnetState;
} double Work::getHour()
{
return Hour;
}
void Work::setHour(double h)
{
Hour = h;
} bool Work::getFinish()
{
return finish;
}
void Work::setFinish(bool f)
{
finish = f;
} void Work::setState(State* s)
{
if (currnetState != )
delete currnetState; currnetState = s;
} void Work::writeProgram()
{
currnetState->writeProgram(this);
}
main.cpp
#include <iostream>
#include <cstdlib>
#include "Work.h"
//#include "State.h" using namespace std; void main()
{
Work emergencyProjects; emergencyProjects.setHour();
emergencyProjects.writeProgram(); emergencyProjects.setHour();
emergencyProjects.writeProgram(); emergencyProjects.setHour();
emergencyProjects.writeProgram(); emergencyProjects.setHour();
emergencyProjects.writeProgram(); emergencyProjects.setHour();
emergencyProjects.writeProgram(); emergencyProjects.setHour();
emergencyProjects.writeProgram(); emergencyProjects.setFinish(false); emergencyProjects.setHour();
emergencyProjects.writeProgram(); emergencyProjects.setHour();
emergencyProjects.writeProgram(); system("pause");
}