Command Pattern – Design Pattern

Commands gives us a way to package a piece of computation(a receiver and a set of actions) and pass it around as a first-class object.
Now, computation may be invoked long after some client application creates the command object.

The process of invoking a command may be done by a different thread. We can take this scenario and apply it to many useful applications such as schedulers, thread pools, and job queues etc.

For understanding command object, Let’s have a example of queue system in Laravel( A php framework ), Queues come to picture when you need to perform a task in background, without affecting the end user experience like as sending a bulk e-mail, or preparing a file to download that will be available after few minutes based on request of end user. In this case we just take the input from end user, what it wishes to do and without completing that request we just intimate to user that specific response will be available or done after a few minutes, mean while what application does, it stores Jobs( implementing queue system methods) or command object, in a database or some other structures depending on your driver configured for queue system.
and then in background we have set some threads that picks the command objects(JOBS) from its pool and gets executed its handle method. As all commands have implemented the Interface that is having handle method, and at time of calling its execute method it calls handle on the command object(JOB class).

We can summarize command pattern as below.

The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable(undo) operations.

It enables encapsulating a request by binding together a set of actions on a specific receiver.

Leave a Reply

Your email address will not be published. Required fields are marked *