版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zxh2075/article/details/82877560
#ifndef __STATE_H__
#define __STATE_H__
#include <iostream>
#include <string>
//状态模式:允许一个对象在其内部状态改变时改变它的行为,使对象看起来似乎修改了它的类。
//状态模式和策略模式比较像,唯一的差别就是状态模式由内部提供接口给外面来进行状态的转换,而策略模式由外部来创建策略实例来调用。
//状态模式中用类表示状态,并为每一种具体的状态都定义一个相应的类,这样可以将复杂的大问题分解为很多小问题分而治之。
//如果不使用状态模式,当接口里的方法比较多时,每个方法内部都进行状态判断是一件很繁琐复杂的事情。
//抽象状态接口
class iState
{
public:
virtual void Proc() = 0;
};
//具体状态
class Morning : public iState
{
public:
virtual void Proc();
};
class Day : public iState
{
public:
virtual void Proc();
};
class Night : public iState
{
public:
virtual void Proc();
};
//上下文类,定义客户端使用的接口并维护一个具体状态的实例
class StateContext
{
public:
StateContext();
virtual ~StateContext();
void ChangeState(iState * state);
void SetHour(int hour);
void Execute();
private:
Morning *m_morning;
Day *m_day;
Night *m_night;
iState *m_state;
};
void TestState();
#endif
#include "State.h"
void Morning::Proc()
{
printf("Now is Morning \n");
}
void Day::Proc()
{
printf("Now is Day \n");
}
void Night::Proc()
{
printf("Now is Night \n");
}
StateContext::StateContext()
{
m_morning = new Morning();
m_day = new Day();
m_night = new Night();
m_state = m_morning;
}
StateContext::~StateContext()
{
delete m_morning;
delete m_day;
delete m_night;
}
void StateContext::ChangeState(iState * state)
{
m_state = state;
}
void StateContext::SetHour(int hour)
{
if (hour < 9 && hour > 4)
{
this->ChangeState(m_morning);
}
else if (hour >= 9 && hour < 18)
{
this->ChangeState(m_day);
}
else
{
this->ChangeState(m_night);
}
}
void StateContext::Execute()
{
m_state->Proc();
}
void TestState()
{
StateContext * sc = new StateContext();
for (int hour=0; hour<23; hour++)
{
sc->SetHour(hour);
sc->Execute();
}
delete sc;
}