23种设计模式---命令模式

命令模式

动机

在软件构建过程中,“行为请求者"与"行为实现者"通常呈现一种"紧耦合”。但在某些场合-比如需要对行为进行"记录、撤销/重(undo/redo)、事务"等处理,这种无法抵御变化的紧耦合是不合适的。
在这种情况下,如何将"行为请求者"与“行为实现者"解耦?将一组行为抽象为对象,可以实现二者之间的松耦合。

解决方法

将一个请求(行为)封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。

例子

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Command
{
public:
    virtual void execute() = 0;
};

class ConcreteCommand1: public Command
{
    string arg;
    
public:
    ConcreteCommand1(const string & a): arg(a) {}
    void execute() override
    {
        cout<< "#1 process..."<<arg<<endl;
    }
};

class ConcreteCommand2: public Command
{
    string arg;
    
public:
    ConcreteCommand2(const string & a): arg(a) {}
    void execute() override
    {
        cout << "#2 process..." << arg << endl;
    }
};

class MacroCommand: public Command
{
    vector<Command*> commands;
public:
    void addCommand(Command *c) { commands.push_back(c); }
    void execute() override
    {
        for (auto &c : commands)
        {
            c->execute();
        }
    }
};

int main()
{
    ConcreteCommand1 command1(receiver, "Arg ###");
    ConcreteCommand2 command2(receiver, "Arg $$$");
    
    MacroCommand macro;
    macro.addCommand(&command1);
    macro.addCommand(&command2);
    
    macro.execute();
}

优缺点

优点:降低了系统耦合度。新的命令可以很容易添加到系统中去。

缺点:使用命令模式可能会导致某些系统有过多的具体命令类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值