Saturday, May 14, 2016

Decorator pattern using lambdas

The patterns mentioned in the book Gang of Four, persist over the time. In fact, although every days appear a lot new tools and frameworks, the base or the principles of the software engineering don't change so often like it seems (fortunately :P ).

Most of the frameworks and tools you are using right now, are an abstraction of the design patterns and concepts that maybe are more old than you. They introduce you another face of the design pattern, usually intending to hide some complexity.

Today, I want to show you guys what shape (face) takes the decorator pattern  when it is implemented with the lambda functionality provided by Java 8. Maybe I think that the key is thinking in the functions like objects.

Let's start. I like so much pizza, specially those days you don't want to cook, which it is quite often.
So you take the phone and call to order a pizza. Your pizza have a price (a base price), for each complement your are adding to your order, the price is increasing.

Take a look to this approach to implement a Order pizza software.



Here is the interesting part. Note that the reduce method is combining all the complements in a chain of calls with the method AndThen.



As you can see this solution has more expressiveness and also avoids the boilerplate code of the traditional way to implement the decorator pattern.

You can find the complete code in my Github profile here
Thank you very much, we keep sharing knowledge.

No comments:

Post a Comment