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

Lets look at it like: When client wants the receiver to execute some task, then client has two options,

  1. Call Receiver and tell him to execute the task.
  2. Call some third party who knows receiver, and third party will pass the message to receiver.

First option looks better, as think of scenario, when there is no waiter to take order in restaurant and you have to go to chef to tell him what you want.

OR suppose you lost your remote and you have to go to TV and manually switch the button.

It provides flexibility so that command can be executed not only in synchronous mode, but also in Asynchronous mode.


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.


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.