状态模式思想:
定义一个状态类,里面可以实现多种状态的转换,每个状态由一个单独类来判断和实现,对象里有设置更新状态的方法,获得当前状态的方法来跳转到其他状态类的方法中(因为setstate的时候把state的状态变为另一个子类,然后调用子类自己的判断方法,满足条件,则用new一个新状态代替原来状态来跳转->使用对象的getstate,此时调用的“当前状态函数”是new出来状态的对象的(即父类的子类方法实现接管- -)) 总结:状态方法判断,达到条件,对象执行set新状态方法,对象get到新状态的Currentstate然后转到新状态自己判断方法中!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class War;
class State
{
public:
virtual void Prophase() {}
virtual void Metaphase() {}
virtual void Anaphase() {}
virtual void End() {}
virtual void CurrentState(War *war) {}
};
//战争
class War
{
private:
State *m_state; //目前状态
int m_days; //战争持续时间
public:
War(State *state)
: m_state(state),
m_days(0)
{}
~War()
{
delete m_state;
}
int GetDays()
{
return m_days;
}
void SetDays(int days)
{
m_days = days;
}
void SetState(State *state)
{
delete m_state; m_state = state;
}
void GetState()
{
m_state->CurrentState(this);
}
};
//战争结束
class EndState: public State
{
public:
void End(War *war) //结束阶段的具体行为
{
cout<<"战争结束"<<endl;
}
void CurrentState(War *war) { End(war); }
};
//后期
class AnaphaseState: public State
{
public:
void Anaphase(War *war) //后期的具体行为
{
if(war->GetDays() < 30)
cout<<"第"<<war->GetDays()<<"天:战争后期,双方拼死一搏"<<endl;
else
{
war->SetState(new EndState());
war->GetState();
}
}
void CurrentState(War *war) { Anaphase(war); }
};
//中期
class MetaphaseState: public State
{
public:
void Metaphase(War *war) //中期的具体行为
{
if(war->GetDays() < 20)
cout<<"第"<<war->GetDays()<<"天:战争中期,进入相持阶段,双发各有损耗"<<endl;
else
{
war->SetState(new AnaphaseState());
war->GetState();
}
}
void CurrentState(War *war) { Metaphase(war); }
};
//前期
class ProphaseState: public State
{
public:
void Prophase(War *war) //前期的具体行为
{
if(war->GetDays() < 10)
cout<<"第"<<war->GetDays()<<"天:战争初期,双方你来我往,互相试探对方"<<endl;
else
{
war->SetState(new MetaphaseState());
war->GetState();
}
}
void CurrentState(War *war) { Prophase(war); }
};
int main()
{
War *war = new War(new ProphaseState());
for(int i = 1; i < 40;i += 5)
{
war->SetDays(i);
war->GetState();
}
delete war;
return 0;
}