Command Pattern — get the gist in 2 min.

aditya chaudhari
JavaDeveloperDiary — JDD
3 min readJul 26, 2022
Command Design Pattern Java

The Command Design Pattern is all about encapsulating a request as an object and passing it as a request parameter.
It decouples the object that invokes the action from the object that performs the action.

It’s a behavioral design pattern that enables you to transfer data as an object between the system components sender and receiver.

Simple Example :
Suppose you want to design a RemoteControl API where the expectation is to create a slots to configure different appliances.
We are going to implement simple light on and off functionality on top of it all other slots can be filled. The goal is to provide the ability to the remote control to configure different slots and respective ON and OFF buttons.

head first design pattern — simple remote control example.

Solution Design :

command pattern simple remote control solution design.

For the entire code please refer this github link .

Components in command pattern and above solution :
Receiver, Command, ConcreteCommands, and Invoker are the main components in the command design pattern.

Receiver : This is actual business logic that is going to wrap into commands.

Command : It’s an interface that declares a simple method usually named execute.

ConcreteCommand: Implements the Command by associating business entity and logic to execute() method.

Invoker: Remember Invoker is not creating the command objbect, it’s just holding a reference of command set by the client and just triggers command execution (Remember Invoker is not directly invoking Light On method instead it just calls execute method on the Command).

Client Class: This is responsible to create a command object and set that to the Invoker (our simple example has only one slot defined for RemoteControl but an improved version can have multiple slots and in client class, we can assign slots along with commands to set to invoker class)

The real fun is in the details, if you wish to know and understand the pros-cons, java-code example for the command pattern then please consider checking the detailed article at [command-pattern-explained-6-min-read]

Thanks for reading. Love IT, Live IT, Enjoy IT.

On the journey to understand the core essence of design patterns.
Every Tuesday I publish a small 2 min post and a long 5–10 min post along with a code example, please consider follow if you wish to get notified!

--

--

aditya chaudhari
JavaDeveloperDiary — JDD

building efficient, scalable and maintainable enterprise e-commerce applications using java, spring framework and SAP CC. Life Mantra → Love IT Live IT Enjoy IT