Command Design Pattern - Is Invoker Optional?

拟墨画扇 提交于 2019-12-09 09:10:48

问题


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?


回答1:


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.




回答2:


As we know, java.lang.Runnable is one of the examples of command pattern where Thread class works as an invoker. We pass object of a Runnable class to Thread class and say start/run.

But we never create a client class which can invoke main thread.

So an invoker is not optional but it is not tightly coupled to client. So UML of command pattern never shows any relationship among client class and invoker class.

Another answer related to this question.



来源:https://stackoverflow.com/questions/12879609/command-design-pattern-is-invoker-optional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!