1.状态模式简介
状态模式:当一个对象的内在状态允许改变其行为,这个对象看起来好像改变了其类。主要用于一个对象的状态转换很复杂时,即含有大量的if else 语句时,可以将状态判断逻辑转移到表示不同状态的类中。这样要增加新状态变化时,只需要新增子类和修改部分类,不同修改整个判断函数。UML类图如下:
2.状态模式实例
书写员工一天工作状态类,工作状态状态和工作时长及任务完成情况有关。其类图如下:
c 实现的代码如下
代码语言:javascript复制#include<exception>
#include <iostream>
#include<string>
using namespace std;
//8.状态模式:员工一日工作状态
class State;
class MorningState;
class NoonState;
class AfternoonState;
class EveningState;
class RestState;
class SleepingSate;
class Work
{
public:
Work(){ m_pState = new MorningState; }
~Work()
{
if (m_pState)
{
delete m_pState;
m_pState = NULL;
}
}
void printState()
{
m_pState->printState(*this);
}
void setState(State *ipState)
{
if (m_pState)
{
delete m_pState;
}
m_pState = ipState;
}
void setHour(int iHour){ m_hour = iHour; };
int getHour(){ return m_hour;}
void setFinished(bool ibFinished){ m_isFinished = ibFinished; };
bool getFinished(){ return m_isFinished; }
protected:
int m_hour;
bool m_isFinished;
State* m_pState;
};
class State
{
public:
~State(){};
virtual void printState(Work w) = 0;
};
class RestState :public State
{
public:
void printState(Work w) override
{
cout << "当前时间:" << w.getHour() << " 任务干完了,下班了!" << endl;
}
};
class SleepingSate :public State
{
public:
void printState(Work w) override
{
cout << "当前时间:" << w.getHour() << " 睡了睡了,累死了!" << endl;
}
};
class EveningState :public State
{
public:
void printState(Work w) override
{
if (w.getFinished())
{
w.setState(new RestState);
w.printState();
}
else if (w.getHour() < 21)
{
cout << "当前时间:" << w.getHour() << " 加班太累了!" << endl;
}
else
{
w.setState(new SleepingSate);
w.printState();
}
}
};
class AfternoonState :public State
{
public:
void printState(Work w) override
{
if (w.getHour() < 17)
{
cout << "当前时间:" << w.getHour() << " 下午状态还不错,继续努力!" << endl;
}
else
{
w.setState(new EveningState);
w.printState();
}
}
};
class NoonState :public State
{
public:
void printState(Work w) override
{
if (w.getHour() < 13)
{
cout << "当前时间:" << w.getHour() << " 饿了,午饭:犯困,午休!" << endl;
}
else
{
w.setState(new AfternoonState);
w.printState();
}
}
};
class MorningState :public State
{
public:
void printState(Work w) override
{
if (w.getHour()<12)
{
cout << "当前时间:" << w.getHour() << " 精神百倍!" << endl;
}
else
{
w.setState(new NoonState);
w.printState();
}
}
};
int main()
{
Work *pw = new Work;
pw->setHour(9);
pw->printState();
pw->setHour(10);
pw->printState();
pw->setHour(12);
pw->printState();
pw->setHour(13);
pw->printState();
pw->setHour(14);
pw->printState();
pw->setHour(17);
pw->setFinished(false);
pw->printState();
pw->setHour(19);
pw->printState();
pw->setHour(22);
pw->printState();
delete pw;
system("pause");
}
3.总结
此时如果状态改变发生变动时,只需要修改一小部分类的实现即可,类似状态机模型。