38

Revised implementation of Strategy Pattern in Java – ITNEXT

 4 years ago
source link: https://itnext.io/how-java-8-killed-the-strategy-pattern-8f226a4ec3c0?source=friends_link&%3Bsk=2533e24d2602aa24402045181e5323da&gi=744e97c58e1e
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Revised implementation of Strategy Pattern in Java

How Java 8 killed the Strategy Pattern

Image for post
Image for post

Image by mcdonaldland.info

By introducing lambda expression in Java 8, many things have changed in Java world and now Java developers can write more concise code and also use functional patterns much easier.

I read a nice article about “How Scala killed the Strategy Pattern” by Alvin Alexander that compares an old Java implementation of Strategy Pattern by Wikipedia with more concise Scala implementation, but that implementation used old Java syntax (prior Java 8) and was very verbose:

Strategy Pattern (prior Java 8)

and Scala implementation of the Strategy Pattern:

Strategy Pattern (Scala)

It isn't a fair comparison because after introducing lambda experession in Java 8, we can reimplement the Strategy Pattern in Java like this:

Strategy Pattern (Java 8)

Or even by using libraries like Vavr, we don't need to define Function3 functional interface and use provided one by Vavr.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK