Command Pattern

by | Oct 8, 2020 | Java

Home » Java » Command Pattern

Introduction

The command pattern is a complex behavioural design pattern that encapsulates all the necessary data for a request under an object. In simpler words, the command pattern is a design pattern that actively converts requests into objects with the commands and method calls of the request embedded in the command object itself.

Work Flow of Command Pattern

The pattern works in a systematic sequence. Initially, a request is passed or wrapped in a command object that will trigger the invoker object it is set out for. The invoker object acts as a bridge between the request and the implementation. It scouts for the object best suited to perform the required operations and passes the request to the concerned object. From this workflow structure, it is quite evident that the command pattern triggers a series of objects to get the operation done.

Definition

As defined by the Gang of Four book, ‘the command pattern encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.’

Example and Code

This example will deal with a simple water cooling system. When the water is hot, the cooling system will be turned on. When the water is cold, the heating system will be turned on.

//Let’s define the command interface

public interface waterCommand {
public void process();
}

//Let us create the two concerete test classes that will implement the water cooling system.

public class WaterHeat implements waterCommand{
Water water
public HeatOn (Water water) {
this.water = water;
}

public void process(){
if(water == “cold”)
water.heat();
}
}

 

public class WaterCool implements waterCommand{
Water water
public CoolOn (Water water) {
this.water = water;
}

public void process(){
if(water == “hot”)
water.cool();
}
}

//This is the recoever class that will process the commands
public class Water{
private boolean heat;
public void heat() {
heat = false;                                       //Water needs to be cooled
}
public void cool() {
heat = true;                                        //Water needs to heated
}
}

When to use the Command Pattern?

This design pattern is preferred when a series of requests has been launched simultaneously and you need callback implemented in your program. The pattern also allows you to deals with requests of varying magnitudes at varying times and in varying orders. A great deal of decoupling also takes place by keeping the invoker method independent of the invoked function.

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author