为什么我们需要一个“接收器”命令设计模式中的类 [英] Why do we need a "receiver" class in the Command design pattern

查看:130
本文介绍了为什么我们需要一个“接收器”命令设计模式中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习指挥设计模式。据我所知,与命令模式总是相关的四个术语是命令,接收者,调用者和客户端。



具体的命令类有一个 execute()方法,而调用者有几个命令。调用者决定何时调用命令的 execute()方法。



当调用 execute()方法时,它调用接收方的方法。然后,接收者进行工作。



我不明白为什么我们需要接收器类?我们可以在 execute()方法中进行工作,似乎接收者类是多余的。



感谢

解决方案

设计模式用于解决软件问题。



在尝试了解解决方案(在这种情况下是命令模式)之前,您必须了解问题。



应用命令模式的问题是在对象A的上下文中客户端)调用对象B(接收方)中的方法,因此接收方是问题的一部分,而不是解决方案的一部分。



命令模式的解决方案或想法提供是将对象(Command)中的A到B的方法调用进行封装,实际上它接近于形式模式定义。当您将请求作为对象进行管理时,您可以解决一些问题或实现某些功能。 (您也将需要其他作品,例如Invoker)



列表可以给你一些很好的例子,说明什么样的问题o特征适合于命令模式。



注意:Comamnd模式不需要解耦,实际上最常见的示例模式实现,客户端需要做一个新的接收器实例,所以我们不能谈论在这里解耦。


I am learning command design pattern. As far as I know, four terms always associated with the command pattern are command, receiver, invoker and client.

A concrete command class has an execute() method and the invoker has a couple of commands. The invoker decides when to call the execute() method of a command.

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

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

Thank in advance.

解决方案

Design patterns are used to solve software problems.

You have to understand the problem before trying to understand the solution (in this case Command pattern)

The problems which command pattern apply are in the context of an object A (client) invoking a method in an object B (receiver), so the Receiver is part of the problem, not part of the solution.

The solution or idea that command pattern offers is to encapsulate the method invocation from A to B in an object (Command), in fact this is close to the formal pattern definition. When you manage a request as an object you are able to solve some problems or to implement some features. (you also will need other pieces like the one called Invoker)

This list can give you some good examples of what kind of problems o features are suitable for command pattern.

note: Comamnd pattern is not necesary about decoupling, in fact the most common example pattern immplementation, the client needs to make a new instance of the receiver so we cannot talk about decoupling here.

这篇关于为什么我们需要一个“接收器”命令设计模式中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆