Implementing Command Design Pattern (Java)
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
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.
Concrete GET Command Class :
Concrete POST Command Class :
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 :
All done! Let’s see them in action from a 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 :)