Command Design Pattern



What is command design pattern ?

Command Design Pattern is a kind of behavioral design patterns. You construct a request as command invoke for target's object method, Provide it with the needed parameters to construct the request.

The target object will execute the command.

Command Design Pattern Usage

Having a unified interface between object commands is one of the best useful features of command design pattern.

for example : In a game where you have multiple objects, and a nuclear weapon destructs all your base, you want all affected game objects in that area to begin destruction.

Each object will destruct in a different way, tanks will explode, men will be killed and torn apart, buildings will collapse and so on.

In this situation with command design pattern, you can tell each object to execute the destruction routine with no additional code, and you don't have to be aware of each object's destruction code.

Command Design Pattern UML Diagram

Command Design Pattern consists of some of concrete classes each one represents a command and implements a unified interface "ICommand"

Each command implements a common method called "Execute" but the each one implements it in a different way.

Command Design Pattern UML Diagram

A consumer program will have a list of objects each one can receive a command. So when the explosion occurs, each one can self-destruct automatically.

a Destruct method can loop throw all the objects in the list and send a command to each one to start the destruction process.

Implementation of Command Design Pattern

The ICommand interface provides a common Execute command, each concrete command class will implement this method

Our Destructible objects has a common destruct method by implementing IDestructible interface, which receives a destruct command we created earlier

The consumer program will parse the desired command to the object to be able to destruct.