Implementing Command Design Pattern (Java)

Vibhor Pareek
3 min readFeb 20, 2021

Behavioural Design Pattern

Introduction

Command design pattern another category of behavioural design pattern is used to abstract actions as commands. The command pattern helps you to build concrete command classes over an interface, separating actions or commands incorporated into your receiver . Let’s look at details of terminologies used in the pattern and design classes.

Terminologies

Receiver : This is actual implementation of commands and receiver is responsible to execute the command.

Command Interface : Interface declaring and abstracting the operation.

Concrete Command Classes : Implementing above interface and have reference to receiver to execute the operation.

Invoker : Takes command object to execute the operation.

Code Walkthrough

Let’s consider a simple example of invoking rest service, which has different methods implemented like GET/PUT/POST/PATCH & DELETE. Considering these methods as commands , how do I write my classes ?

Firstly, I will build my receiver class which has actual implementation of commands in our case i.e GET & POST

Receiver Class

OK! Now I have receiver class implemented. Let’s try to create an interface defining the operation which will have an execute method to be implemented by concrete command classes.

Command Interface

Concrete GET Command Class :

Concrete Command Class-1

Concrete POST Command Class :

Concrete Command Class-2

In each of the above command classes, I am passing a reference of receiver for executing the command/action or business logic.

Lastly, Invoker class which will just set command at runtime taking command interface as a reference :

Invoker Class

All done! Let’s see them in action from a client class.

Client Class

Take Aways & Advantages

  • This way you can also implement other methods like PUT/PATCH and call them at runtime with just setting the command object.
  • Makes our code scalable, easy to understand as well as loose coupled which is open to extension and closed for modification :)

Hope you have enjoyed reading the article! Keep learning :)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Vibhor Pareek
Vibhor Pareek

No responses yet

Write a response