Command Pattern seems needlessly complex (what am I failing to understand?)

前端 未结 4 1852
你的背包
你的背包 2020-12-11 01:26

I\'ve read up on the Command Pattern, and I think I\'m missing something. The Command object exists to abstract away the details of the Receiver object. It seems to me tha

4条回答
  •  长情又很酷
    2020-12-11 01:58

    We've already hidden the details of the Receiver behind the Command,

    That's exactly right, but who is hiding those details and who are they hidden from? The answer is that whomever instantiates the Command implementation is doing the hiding, and whomever invokes the Command abstraction is hidden from. Clearly it makes no sense for both of those actions to be performed by one object, any more than you can hide something from yourself.

    Thus, the Client instantiates a ConcreteCommand and passes it to the Invoker, who is only aware of the Command interface. In effect, the Client performs dependency injection for the Invoker.

    Also note there are different ways to implement a ConcreteCommand (see https://stackoverflow.com/a/35617012/1371329). If the ConcreteCommand has some mechanism to dynamically discover its own Receiver, then dependency injection may be unnecessary.

提交回复
热议问题