Command Pattern example

Command pattern

Command pattern is a data driven design pattern and falls under behavioral pattern category. The official definiation of the command pattern according the Gang of Four:

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations

What...what does that mean....?

Well it just mean you have an ojbect that want to execute a request. Something like: add an address to the list of addresses. In this case you need to have an object: order and an object which hold the list with addresses and a function which adds the address to the list of addresses. This is all thightly coupled. If there is a need for a new function, maybe to put an addres on nonactive for example, then there is a code change needed on an excisting piece of code. This is violating the open/closed principe which is defined in the Solid principles

So to prevent this you can make use of the command pattern design. In this case you divide the logic over different actors: a client, a receiver, and a invoker. And of course there is the command ( the add address or put address on hold command ) which inherits from a abstract command.

Command pattern design example

To make things simple I created a Github repository with an easy implementation of the command pattern: Github command example repository 

Command pattern advantages

So now we understand how it works. But what are advantages:

  1. Extensions to add a new command is easy and can be done without changing the existing code
  2. It allows you to create a sequence of commands by providing a queue system
  3. It decouples the classes that invoke the operation from the object that knows how to execute the operation
  4. You can also define a rollback system with the Command pattern, for example, in the Wizard example, we could write a rollback method

Command pattern dis-advantages

Coding the command pattern comes with a cost, here are the disadvantages :

    There are a high number of classes and objects working together to achieve a goal. Application developers need to be careful developing these classes correctly.

Meaning: implementing and coding the command pattern can be complicated and will cost effort and time. Especially when you application doesn need one of the mentioned advantages maybe you need to reconcider the use of the command pattern.

Resources

Github repository with an easy implementation of the command pattern: Github command example repository 

Gang of four patterns: Gang of four patterns

Pluralsight: Command pattern explanation.

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!