Answer the question
In order to leave comments, you need to log in
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?
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
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
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 questionAsk a Question
731 491 924 answers to any question