c++状态模式

2021-02-17  本文已影响0人  一路向后

1.状态模式简介

   允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类,(State Pattern)是设计模式的一种,属于行为模式。

2.源码实现

#include <iostream>

using namespace std;

class Context;

class State
{
public:
    virtual void Handle(Context *p) = 0;
};

class ConcreteStateA : public State
{
public:
    virtual void Handle(Context *pContext)
    {
        cout << "I am concrete state A" << endl;
    }
};

class ConcreteStateB : public State
{
public:
    virtual void Handle(Context *pContext)
    {
        cout << "I am concrete state B" << endl;
    }
};

class Context
{
public:
    Context(State *pState) : m_pState(pState){};

    void Request()
    {
        if(m_pState)
        {
            m_pState->Handle(this);
        }
    }

    void ChangeState(State *pState)
    {
        m_pState = pState;
    }

private:
    State *m_pState;
};

int main(int argc, char **argv)
{
    State *pStateA = new ConcreteStateA();
    State *pStateB = new ConcreteStateB();
    Context *pContext = new Context(pStateA);

    pContext->Request();
    pContext->ChangeState(pStateB);
    pContext->Request();

    delete pContext;
    delete pStateA;
    delete pStateB;

    return 0;
}

3.编译源码

$ g++ -o example example.cpp

4.运行及其结果

$ ./example
I am concrete state A
I am concrete state B
上一篇下一篇

猜你喜欢

热点阅读