Why do we need the "receiver" class in the command design template

I am studying a team design template. As far as I know, the four terms always associated with a team template are team, recipient, invoker, and client.

A particular class of commands has an execute() method, and invoker has several commands. Invoker decides when to call the execute() method of a command.

When the execute() method is called, it calls the receiver method. Then the receiver does the work.

I don’t understand why a receiver class is needed? We can do the work inside the execute() method, it seems that the receiver class is redundant.

Thanks in advance.

+4
source share
3 answers

Design patterns are used to solve software problems.

You need to understand the problem before trying to understand the solution (in this case, the command template)

The problems with which the command template is applied relate to object A (client) calling the method in object B (receiver), so the receiver is part of the problem, not part of the solution.

The solution or idea proposed by the command template is to encapsulate a method call from A to B into an object (Command), in fact this is close to the formal definition of the template. When you manage the request as an object, you can solve some problems or implement some functions. (you will also need other parts such as Invoker)

This list can give you some good examples of what problems o functions are suitable for the command template.

Note: the Comamnd template is not required for decoupling, in fact the most common example of template implementation, the client needs to create a new recipient instance, so we can not talk about decoupling here.

+7
source

Template purpose is to separate the call from the recipient.

The receiver must do the work, not the command itself, the command simply knows which receiver method is being called, or the command can execute other commands. Using the team template, invoker does not know what is called the expected team.

Thus, a command can be reused by many invokers to perform the same action on the receiver.

+6
source

Imagine a class that can do a couple of things, such as Duck, it can eat and quack. In this example, the duck is the receiver. To apply the team template here, you must be able to wrap the food and quack into the team. They must be separate classes that are derived from the base Command class using the execute() method, since Duck can have only one execute() method. Therefore, EatCommand.execute() calls Duck.eat() and QuackCommand.execute() calls Duck.quack() .

+5
source

Source: https://habr.com/ru/post/1480896/


All Articles