Search code examples
oopdesign-patternscommand-pattern

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.


Solution

  • 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.