Due to the current inclusion of Java 8 Functional Programming Paradigm in today’s world, people still wonder how it could collaborate well with the existing object oriented approach. That’s why I would love to demonstrate a concrete example of command pattern using Java 8 Lambda Expression.
Command Pattern
The Problem Domain
An editor or IDE has gallons of actions or commands such as open, close, save etc. Each and every time, someone needs to develop a new command for the IDE, it should conform to the Open-Closed principle - Open for Extension and Closed for Modification. So, now our design decision should be effective enough to allow extensions to the applications so that anyone can easily plug-in new command to the IDE.
OOP way
First of all, I would love to tell you about how it can be achieved using the object oriented way.
Command
Concrete Command - Open
Concrete Command - Save
Receiver
Concrete Receiver
Invoker
Client
Functional Way
So far, we have seen the object-oriented approach in solving our defined problem using Command Pattern. Now, we would try to solve it using Functional Programming Paradigm which I believe would be more concise and better solution.
Command
Receiver
Invoker
Client
Benefits
You can clearly see that I didn’t write any concrete implementation class of the commands. I have only passed those implementations as behaviors to the record method as it accepts SAM (Single Abstract Method) Interface (Command).