状态模式:允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。它有两种使用情况:(1)一个对象的行为取决于它的状态, 并且它必须在运行时刻根据状态改变它的行为。(2)一个操作中含有庞大的多分支的条件语句,且这些分支依赖于该对象的状态。
使用场景
1、一个对象的行为取决于它的状态,并且它必须在运行时刻根据状态改变它的行为;
2、一个操作中含有庞大的多分支的条件语句,且这些分支依赖于该对象的状态。这个状态通常用一个或多个枚举常量表示。通常有多个操作包含这一相同的条件结构。State模式将每一个条件分支放入一个独立的类中。这使得你可以根据对象自身的情况将对象的状态作为一个对象,这一对象可以不依赖于其它对象而独立变化。
#include<iostream>
using namespace std;
class Context;
class State
{
public:
virtual void handle(Context* pContext) = 0;
};
class StateA : public State
{
public:
void handle(Context * pContext)
{
cout << "I am state A" << endl;
}
};
class StateB : public State
{
public:
void handle(Context * pContext)
{
cout << "I am state B" << endl;
}
};
class Context
{
public:
Context(State * state):m_pState(state){}
void Request()
{
if(m_pState)
{
m_pState->handle(this);
}
}
void ChangeState(State * state)
{
m_pState = state;
}
private:
State * m_pState;
};
int main()
{
State * stateA = new StateA();
State * stateB = new StateB();
Context * pcontext = new Context(stateA);
pcontext->Request();
pcontext->ChangeState(stateB);
pcontext->Request();
delete stateA;
delete stateB;
delete pcontext;
return 0;
}
以战争为例,假设一场战争需经历四个阶段:前期、中期、后期、结束。当战争处于不同的阶段,战争的行为是不一样的,也就说战争的行为取决于所处的阶段,而且随着时间的推进是动态变化的。
#include<iostream>
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 << "war end "<< endl;
}
void CurrentState( War * war ) { End(war); }
};
class AnaphaseState : public State
{
public:
void Anaphase(War * war)
{
if(war->GetDays() < 30)
{
cout << "The " << war->GetDays() << "days war anaphase" << 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 << "The " << war->GetDays() << "days war metaphase" << 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 << "The "<< war->GetDays() <<" days war prophase"<< 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;
}