user1164937
user1164937

Reputation: 2117

Command pattern use case?

What are some example use cases where the command pattern may be of use? I've been reading about it, and I have a good idea on how to implement it. But It's a big vague when it comes to knowing when to use it.

One of the problems it solves is to decouple the API of a class. But what does that imply exactly? What's the disadvantage of calling an object's methods directly?

What other problems does it solve, and how do they benefit from it?

Upvotes: 0

Views: 3017

Answers (2)

Daniele Pallastrelli
Daniele Pallastrelli

Reputation: 2552

Command pattern is useful when you need to treat an action as an object, so that you can:

  • add new action types withouth switch case construct (read: plugin)
  • store the action to be exectute later (eg., active object)
  • associate to the action complementary info (e.g., how to undo the action)

A simple example of command pattern in real code is the following.

When implementing a protocol, you can use the command pattern to decouple the parsing of a byte stream from the action associated to the message (remember that in OO you don't manage messages, but messages manage themselves :-)

When the channel receives some byte from the wire, it constructs the right command object (e.g., using the prototype or abstract factory pattern) and put it in a queue to be executed later (possibly in another thread).

Upvotes: 3

Dario
Dario

Reputation: 4035

The command pattern can help you in terms of extensibility as you can add a new use cases without changing the existing code.

It also permits you to chain commands and execute it in sequential or parallel mode (dependings of the language capabilities) and create macros.

You can see more examples in this page: http://gameprogrammingpatterns.com/command.html

Upvotes: 0

Related Questions