State 状态模式

动机

  • 在软件构件过程中,某些对象的状态如果改变,其行为也随之发生变化

定义

  • 允许一个对象在其内部状态改变时改变它的行为,从而使对象看起来似乎修改了其行为

要点

  • State模式将所有与一个特定状态相关的行为都放入一个State的子类对象中,在对象状态切换时,切换相应的对象;但同时维持State的接口,这样实现了具体操作与状态转换之间的解耦
  • 为不同的状态引入不同的对象使得状态转换变得更加明确,而且可以保证不会出现状态不一致的情况

示例

#include 

class CBaseState
{
public:
    CBaseState() : pNext_(nullptr) {}
    virtual ~CBaseState() {}
    
    virtual void Deal() = 0;
    CBaseState* GetNext() { return this->pNext_; }

protected:
    CBaseState* pNext_;
};

class CState0 : public CBaseState
{
public:
    virtual void Deal();
};
class CState1 : public CBaseState
{
public:
    virtual void Deal();
};
class CState2 : public CBaseState
{
public:
    virtual void Deal();
};

void CState0::Deal()
{
    printf("State0 Deal\n");
    this->pNext_ = new CState1;
}
void CState1::Deal()
{
    printf("State1 Deal\n");
    this->pNext_ = new CState2;
}
void CState2::Deal()
{
    printf("State2 Deal\n");
    delete this->pNext_;
    this->pNext_ = nullptr;
}

class CTest
{
public:
    CTest(CBaseState* pState) : pState_(pState) {}

    void DealState()
    {
        pState_->Deal();
        pState_ = pState_->GetNext();
    }

private:
    CBaseState* pState_;
};

int main()
{
    CTest Test0(new CState0);
    Test0.DealState();
    Test0.DealState();
    Test0.DealState();
    /*
    State0 Deal
    State1 Deal
    State2 Deal
    */

    CTest Test1(new CState1);
    Test1.DealState();
    Test1.DealState();
    /*
    State1 Deal
    State2 Deal
    */

    return 0;
}

https://www.bilibili.com/video/av24176315/?p=18

你可能感兴趣的:(State 状态模式)