S8.命令模式

2022-01-03  本文已影响0人  开源519

命令模式

命令模式是一种行为模式,用于将请求或频繁调用关系管理起来,封装成对象行为。

意义

在平常的设计中,对于不同模块之间调用关系,通常通过头文件直接调用接口即可。随着需求的增多,调用越来越多。最终维护起来会发现如下问题:

命令模式可以解决以上问题。

类图

命令模式

Invoker:

执行实例,此对象完成命令申请和命令响应的整个流程。

Command:

命令对象基类,定义命令类的模板。

LedCmd、MotorCmd:

具体的命令类,其内部会持有Receiver的指针,用于将具体的命令实例和响应实例绑定。此类中,可以做一些对命令的管理等操作。

Receiver:

命令响应类,用于响应某个命令的执行动作。

Client:

客户端代码,如果规范起来的话,Client应只能访问对外释放的接口。在此指定命令与指定响应行为绑定。

总结

源码

#include <iostream>
#include <string>

using namespace std;

// 命令响应
class Receiver
{
public:
    explicit Receiver(string operation)
    {
        mOperation = operation;
    }

    void Action()
    {
        cout << mOperation << endl;
    }

private:
    string mOperation;
};

class Command
{
public:
    virtual ~Command()
    {

    }

    virtual void Execute() = 0;

protected:
    Command()
    {

    }
};

class LedCmd : public Command
{
public:
    void Execute()
    {
        if (NULL != mRcv) {
            this->mRcv->Action();
        }
    }

    explicit LedCmd(Receiver *pRcv)
    {
        if (NULL != pRcv) {
            mRcv = pRcv;
        }
        else
        {
            mRcv = NULL;
            cout << "Error: Param failed!" << endl;
        }
    }

private:
    Receiver *mRcv;
};

class MotorCmd : public Command
{
public:
    void Execute()
    {
        if (NULL != mRcv) {
            this->mRcv->Action();
        }
    }

    explicit MotorCmd(Receiver *pRcv)
    {
        if (NULL != pRcv) {
            mRcv = pRcv;
        }
        else
        {
            mRcv = NULL;
            cout << "Error: Param failed!" << endl;
        }
    }

private:
    Receiver *mRcv;
};

class Invoker
{
public:
    explicit Invoker(Command *pCmd)
    {
        if (NULL != pCmd)
        {
            mCmd = pCmd;
        }
        else
        {
            mCmd = NULL;
            cout << "Error: Param failed!" << endl;
        }
    }

    // 所有的命令响应动作都会经此接口触发, 可以在此处实现对命令的管理设计
    void Invoke()
    {
        if (NULL != mCmd) {
            mCmd->Execute();
        }
        else {
            cout << "Error: no action" << endl;
        }
    }

private:
    Command *mCmd;
};

int main(int argc, char *argv[])
{
    Receiver *theLedRcv = new Receiver("Led");
    LedCmd *theLedCmd = new LedCmd(theLedRcv);
    Invoker *theLedManager = new Invoker(theLedCmd);
    theLedManager->Invoke();

    Receiver *theMotorRcv = new Receiver("Motor");
    LedCmd *theMotorCmd = new LedCmd(theMotorRcv);
    Invoker *theMotorManager = new Invoker(theMotorCmd);
    theMotorManager->Invoke();

    delete theLedRcv;
    delete theLedCmd;
    delete theLedManager;

    delete theMotorRcv;
    delete theMotorCmd;
    delete theMotorManager;

    return 0;
}
$ ./a.out 
Led
Motor
上一篇 下一篇

猜你喜欢

热点阅读