设计模式之状态模式(State)

时间:2022-01-21 22:00:27

状态模式原理:随着状态的变化,对象的行为也发生变化

代码如下:

#include <iostream>
#include <string>
#include <list>
using namespace std; class War;
class State
{
public:
virtual void fire(War *war)
{ }
}; class War
{
public:
War(State* state):m_state(state),m_day(0){}
void Setday(int day)
{
m_day = day;
}
int Getday()
{
return m_day;
}
void SetState(State *state)
{
delete m_state;
m_state = state;
}
void GetState()
{
m_state->fire(this);
}
~War(){delete m_state;}
private:
State *m_state;
int m_day;
}; class WarEndState:public State
{
public:
virtual void fire(War *war)
{
cout << "we are in the end of war" <<endl;
}
}; class WarMiddleState:public State
{
public:
virtual void fire(War *war)
{
if (war->Getday() < 20)
{
cout << "we are in the middle of war" <<endl;
}
else
{
war->SetState(new WarEndState());
war->GetState();
}
}
}; class WarBeforeState:public State
{
public:
virtual void fire(War *war)
{
if (war->Getday() < 10)
{
cout << "we are in the before of war" <<endl;
}
else
{
war->SetState(new WarMiddleState());
war->GetState();
}
}
}; int main()
{
War *war = new War(new WarBeforeState());
for (int i = 9;i < 30;i+=9)
{
war->Setday(i);
war->GetState();
}
return 0;
}