状态模式主要用在对象的状态随外界因数而改变,对象的状态改变后其动作也随之改变。通常设计状态机的时候会用到。

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <iostream>

using namespace std;
class war;
class state{
public:
virtual void fighting(war *pwar) = 0;
virtual ~state(){};
state(){};
};

class war{
int ndays;
state *m_curstate;
public:
war(state *ste)
{
m_curstate = ste;
ndays = 0;
}
void setDay(int day) {
ndays = day;
}
int getDay() {
return ndays;
}
void getState() {
m_curstate->fighting(this);
}
void setState(state *ste) {
if (m_curstate) delete m_curstate;
m_curstate = ste;
}
};

class endState : public state {

void fighting(war *pwar)
{
cout << "老大:\"刚开始是哪个小混蛋挑事的,拉出来。妹的,你轻点包扎,疼死了。\"" <<endl;
cout << "老大:\"这个护士业务能力好差,拉出去让小弟们解解乏。\"" <<endl;
}
};

class tailState : public state {
void fighting(war *pwar)
{
cout << "士兵乙:\"老大,他们去拿砍刀了。\"" <<endl;
cout << "老大:\"兄弟们,撤!\"" << endl;

if (pwar->getDay() >= 10)
{
pwar->setState(new endState());
}
}
};

class middleState : public state{

void fighting(war *pwar)
{
cout << "士兵甲:\"老大,好多兄弟们受伤了。\"" << endl;
cout << "老大:\"兄弟们坚持住,对方快坚持不住了。\"" << endl;
if (pwar->getDay() >= 7)
{
pwar->setState(new tailState());
}
}

};


class beginState : public state{
void fighting(war *pwar)
{
cout << "老大:\"兄弟们抄家伙,干死他们!\"" << endl;

if (pwar->getDay() >= 4)
{
pwar->setState(new middleState());
}
}
};

class preState : public state{
void fighting(war *pwar)
{
cout << "有个士兵向领导报告:\"老大,有人挑事!\"" <<endl;
if (pwar->getDay() >= 3)
{
pwar->setState(new beginState());
}
}
};

int main()
{
preState *pre = new preState();
war westWar(pre);

for (int n = 0; n < 15; n++)
{
westWar.getState();
westWar.setDay(n);
sleep(10);
}
return 0;
}