Java Magazine, Nov/Dec 2016
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 55 new to java New language features often make existing code patterns or idioms less popular For example the introduction of the for each loop in Java 5 replaced many uses of explicit iterators because its less error prone and more concise The introduction of the diamond operator in Java 7 reduced the use of explicit generics at instance creation and slowly pushed Java programmers toward embracing type inference In this article we examine how lambdas can reduce the code needed to implement several programming patterns To follow along youll need a basic familiarity with lambdas A specific class of patterns is called design patterns They are a reusable blueprint if you will for a common problem when designing software Its a bit like how construction engineers have a set of reusable solutions to construct bridges for specific scenarios such as suspension bridge arch bridge and so on For example the visitor design pattern is a common solution for separating an algorithm from a structure on which it needs to operate Another pattern the singleton pattern is a common solution to restrict the instantiation of a class to only one object Lambda expressions provide yet another new tool in the programmers toolbox They can provide alternative solutions to the problems the design patterns are tackling but often with less work and in a simpler way Many existing objectoriented design patterns can be made redundant or written in a more concise way using lambda expressions In this section we explore design patterns Strategy Template method Observer Factory We show how lambda expressions can provide an alternative way to solve the same problem for which each of these design patterns is intended Strategy Pattern The strategy pattern is a common solution for representing a family of algorithms and letting you choose among them at runtime You can apply this pattern to a multitude of scenarios such as validating an input with different criteria using different ways of parsing or formatting an input The strategy pattern consists of three parts as illustrated in Figure 1 These parts are An interface to represent some algorithm the interface Strategy One or more concrete implementations of that interface to represent multiple algorithms the concrete classes ConcreteStrategyA and ConcreteStrategyB One or more clients that use the strategy objects RAOUL GABRIEL URMA MARIO FUSCO AND ALAN MYCROFT Implementing Design Patterns with Lambdas Astute use of lambdas can greatly reduce the complexity of implementing standard coding patterns
You must have JavaScript enabled to view digital editions.