设计模式之——状态模式

state.h

#ifndef STATE_H
#define STATE_H

#include <QtDebug>
#include "context.h"

class Context;

class State
{
public:
    State() {}
    virtual void doAction()=0;
};

class StartState : public State
{
public:
    StartState (Context *context) {this->context=context;}
    void doAction();

private:
    Context *context;
};

class StopState : public State
{
public:
    StopState(Context *context){this->context=context;}
    void doAction();

private:
    Context *context;
};

#endif // STATE_H

context.h

#ifndef CONTEXT_H
#define CONTEXT_H

#include "state.h"

class Context
{
public:
    Context()
    {
        m_start = new StartState(this);
        m_stop = new StopState(this);
        m_state = m_start;
    }
    void setState(State *state)
    {
        m_state = state;
    }

    State *getStart()
    {
        return m_start;
    }

    State *getStop()
    {
        return m_stop;
    }

    void doAction()
    {
        m_state->doAction();
    }

private:
    State *m_start,*m_stop,*m_state;

};

void StartState::doAction()
{
    qDebug() << "关闭";
    this->context->setState(this->context->getStop());
}

void StopState::doAction()
{
    qDebug() << "开始";
    this->context->setState(this->context->getStart());
}

#endif // CONTEXT_H

main.cpp

#include <QApplication>
#include <QtDebug>

#include "context.h"
#include "state.h"

//状态模式
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Context *context=new Context();
    context->doAction();
    context->doAction();
    context->doAction();
    context->doAction();

    return a.exec();
}

输出结果

关闭 
开始 
关闭 
开始 

上述代码还有C++的特色,各个具体状态中,所对应转换状态方法,只能在类外实现,而不能在直接在StartState 与StopState里面实现。因为C++不像java,Java编译的时候一次性把所有东西读进去。C++是见一行读一行。这里Context类用到State,StartState 与StopState用到了Context,类间相互调用在C++中是不行的。
参考:https://blog.csdn.net/yongh701/article/details/49154439

UML
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值