美文网首页
c++状态模式

c++状态模式

作者: 一路向后 | 来源:发表于2021-02-17 21:12 被阅读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
    

    相关文章

      网友评论

          本文标题:c++状态模式

          本文链接:https://www.haomeiwen.com/subject/gzjwxltx.html