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

aneuryzm picture aneuryzm · Jun 9, 2011 · Viewed 9.9k times · Source

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.

Answer

Robert Levy picture Robert Levy · Jun 9, 2011

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.