命令设计模式 - Invoker可选? [英] Command Design Pattern - Is Invoker Optional?

查看:137
本文介绍了命令设计模式 - Invoker可选?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Invokeer类在命令设计模式中是否可选?客户端需要实例化具体命令和接收器的命令。客户端总是需要实例化Invoker并将命令对象传递给Invoker对象。以后每当客户端需要执行命令时,客户端就会询问Invoker对象,Invoker会执行命令(可能立即执行或者可能排队该命令以备后续执行)。



或者是这样呢?如果客户端需要同步执行命令,客户端将使用基类接口引用该命令,但会实例化具体的命令和接收器。每当客户端需要执行命令时,客户端将只调用基类命令变量的execute方法?当需要一些额外的逻辑时,一个命令应该被执行,Invoker类将被用来保持额外的逻辑和客户端将与Invoker对象进行交互以执行命令?

解决方案

命令模式的目的通常是1)使一组不同的操作共享相同的类型,以便它们可以被相同的代码处理2)单独的操作编组/创建从操作调用。收件人是明确要求的目的2.



如果您在创建后立即调用,或者如果Reciever正在扮演调用者的角色,则没有单一用途,独立调用。这是否意味着没有调用者真的是一个哲学问题:)



以这种方式看待:你/可以/分开创建,调度和调用。这并不意味着你必须将它们实现为三个不同的类。这只是命令模式生命周期中涉及的逻辑角色。



编辑:我猜单一责任原则认为你应该分开它们,但是有一个这样的事情作为感觉:)本地条件可以而且应该遵守。


Is Invoker class optional in Command design pattern? Client needs to instantiate Concrete Command and Receiver for the command. Does client always need to instantiate Invoker and pass on the command object to Invoker object. Later on whenever client needs to execute the command, client just asks Invoker object and Invoker performs the command (maybe immediately or may queue the command for later execution).

Or is this other way around? If client needs to perform the command synchronously, client will reference the command using base class interface but will instantiate concrete command and receiver. Whenever client will need to perform the command, client will just call the execute method on base class command variable? When there will be a need of some additional logic of when a command should get executed, Invoker class will be used to keep that additional logic and client will interact with Invoker object to perform the command?

解决方案

The purposes of Command pattern are usually 1) Make a set of different operations share the same type so they can be processed by the same code 2) separate operation marshalling/creation from operation invocation. The Reciever is explicitly required for purpose 2.

If you invoke right after creation or if the Reciever is playing the role of invoker, there's no single-purpose, stand-alone invoker. Whether that means that there's no invoker is really a philosophical question :)

Look at it this way: You /can/ seperate the creation, scheduling and invocation. That doesn't mean that you have to implement them as three separate classes. It's just the logical roles that are involved in the Command pattern life cycle.

EDIT: I guess the single responsibility principle argues that you should separate them, but there's such a thing as commen sense :) Local conditions can and should be observed.

这篇关于命令设计模式 - Invoker可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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