Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

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

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 that we could simply stop here, and hold references to Command objects to execute the appropriate method at the appropriate time.

Why, then, is the Invoker needed? What advantage does this additional indirection provide? We've already hidden the details of the Receiver behind the Command, what's the motivation for the Command to then be hidden from the client as well?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are passing different type of commands, Invoker is useful. You can use same Invoker for execution of different concrete commands. On a different node, tagging Receiver with ConcreteCommand instead of Invoker allows loose coupling. The Receiver may change the name of the method (e.g. switchOn to swithcOnTV) as in this example:

Related post: Using Command Design pattern

To understand the purpose of Invoker,I would like you to refer this article on Restaurant & Car Service centre use cases.

The waiter (Invoker) takes the order from the Customer on his pad. The Order is then queued for the order cook and gets to the cook (Receiver) where it is processed.

The Client is the Customer. He sends his request to the Receiver through the waiter, who is the Invoker. The waiter encapsulates the command (the order in this case) by writing it on the check and then places it, creating the ConcreteCommand object which is the command itself.

The Receiver will be the cook that, after completing work on all the orders that were sent to him before the command in question, starts work on it.

Another noticeable aspect of the example is the fact that the pad for the orders does not support only orders from the menu, so it can support commands to cook many different items.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...