E
E
egorggegor2019-08-20 19:18:01
OOP
egorggegor, 2019-08-20 19:18:01

Did I understand the Command pattern correctly?

Hello everyone, I decided to study the Command pattern, do I understand correctly, it wraps the commands themselves into objects, which adds flexibility to the program?
5d5c1c19677f5701960897.png
Invoker itself is the main one here, which casts everything?) That is, it must have methods for executing any commands, or do we ourselves set the command that Invoker must execute?
(As I understand it, the pattern should look like this, tell me if I understand correctly?)

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

class Receiver {
public:
    void Command1() {};
    void Command2() {};
};

class ConcreteCommand1 : public Command {
public:
    ConcreteCommand1(Receiver* other_purpose): purpose(other_purpose) {};
    void Execute() {
        purpose->Command1();
    }
private:
    Receiver* purpose;
};

class ConcreteCommand2 : public Command {
public:
    ConcreteCommand2(Receiver* other_purpose): purpose(other_purpose) {};
    void Execute() {
        purpose->Command2();
    }
private:
    Receiver* purpose;
};

class Invoker {
public:
    void SetCommand(Command* other_cmd) {
        this->cmd = other_cmd;
    }
    void ExecuteCommand() {
        this->cmd->Execute();
    }
private:
    Command* cmd;
};

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2019-08-20
@egorggegor

The main thing to understand is that there are two classes:
1. Command
2. Handler.
The command is passed to the handler and the "process" method is called already in the handler. To understand in more detail how it works in practice and why it is needed, I suggest reading about CQRS
https://blog.byndyu.ru/2014/05/blog-post.html
https://blog.byndyu.ru/2014/07 /command-and-query-r...
And an example of how it's done in PHP

S
Sergey Egorov, 2019-08-23
@SergeyEgorov

Did you decide to learn all the patterns at once? The essence of the command template is that any behavior can be encapsulated inside, and it can be unified by any user:

public interface Command
{
  void execute();
}

public class FindUserCommand : Command
{
  public void execute()
  {
    /// Здесь у нас код, который ищет пользователя
  }
}

public class DeleteUserCommand : Command
{
  public void execute()
  {
    /// А здес у нас код, который удаляет пользователя
  }
}

FindUserCommand findUser = new FindUserCommand();
DeleteUserCommand deleteUser = new DeleteUserCommand();

/// Поскольку оба этих класса реализуют абстракцию Command
/// мы можем поместить их экземпляры например в коллекцию
 
HashSet<Command> commands = new HashSet<Command>();
commands.Add(findUser);
commands.Add(deleteUser);

/// И отдать затем эту коллекцию кому-нибудь, кто вообще 
/// ничего не знает про FindUserCommand и DeleteUserCommand
/// а знает только про Command. И не смотря на это, этот кто-то
/// совершенно спокойно может выполнить инкапсулированное 
/// внутри команд поведение.

foreach(Command command in commands)
{
  command.execute();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question