设计模式(二十二)command

来源:互联网 发布:java一定要去培训班吗 编辑:程序博客网 时间:2024/05/19 03:45

1.使用场景:将行为请求者和行为实现者解耦,将一组行为抽象为对象,可以实现二者之间的松耦合
2.定义:讲一个请求封装为一个对象,从而使你可以用不同的
请求对客户进行参数化。。。

command设计模式:

#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();}