Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Command Pattern convenient in Object-Oriented Design?

I don't understand why a Command pattern is convenient in object-oriented design.

Instead of using, e.g. the Command Switch which has a reference to the Lamp class, can't I just create a Switchable abstract class and invoke its methods?

In this way I'm decoupling the invoker and receiver anyway, and I don't have to create a Command object for each receiver class.

like image 651
aneuryzm Avatar asked Jun 09 '11 13:06

aneuryzm


People also ask

Why is Command pattern useful?

The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parametrized with different requests. The "check" at a diner is an example of a Command pattern. The waiter or waitress takes an order or command from a customer and encapsulates that order by writing it on the check.

What is the motivation behind using Command design pattern?

The main motivation for using the Command pattern is that the executor of the command does not need to know anything at all about what the command is, what context information it needs on or what it does. All of that is encapsulated in the command.

What is the important property of pattern command in part design?

Definition: The command pattern encapsulates a request as an object, thereby letting us parameterize other objects with different requests, queue or log requests, and support undoable operations.

How does the Command design pattern work?

Command Pattern. In command pattern, the request is send to the invoker and invoker pass it to the encapsulated command object. Command object passes the request to the appropriate method of Receiver to perform the specific action. The client program create the receiver object and then attach it to the Command.


2 Answers

Your Switchable creates an abstraction between invoker and receiver but they are still coupled (invoker has needs a reference to the receiver). The Command pattern lets you create that decoupling. The invoker says to some intermediate component "Hey I've got this command I'd like to be executed" and then the intermediate thing can dynamically pass that request on to the receiver.

ps... I'm guessing you pulled the Switch example from wikipedia. That's a pretty bad example of why this pattern is useful. Take a look at a better examples.

like image 129
Robert Levy Avatar answered Oct 03 '22 22:10

Robert Levy


Suppose you want to make a list like this:

  • Turn on lamp
  • Set A/C temperature
  • Play "Moon River"

The actions and receivers are all different, so you need an abstraction that is decoupled from all of them. The Command pattern also comes in handy when you want to support undo/redo or similar things.

like image 29
kevin cline Avatar answered Oct 03 '22 20:10

kevin cline