Java Reference
In-Depth Information
This was made possible by introducing the functional interface BufferedReader-Processor,
which lets you pass different lambdas to work with a BufferedReader object.
In this section, you've seen how to apply different recipes to improve the readability and
flexibility of your code. You'll now see how lambda expressions can often remove boilerplate
code associated with common object-oriented design patterns.
8.2. Refactoring object-oriented design patterns with lambdas
New language features often make existing code patterns or idioms less popular. For example,
the introduction of the for-each loop in Java 5 has replaced many uses of explicit iterators
because it's less error prone and more concise. The introduction of the diamond operator <> in
Java 7 has reduced the use of explicit generics at instance creation (and slowly pushed Java
programmers toward embracing type inference).
A specific class of patterns is called design patterns. [ 3 ] They're a reusable blueprint, if you will,
for a common problem when designing software. It's 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. The singleton pattern is a
common solution to restrict the instantiation of a class to only one object.
3 See http://c2.com/cgi/wiki?GangOfFour .
Lambda expressions provide yet another new tool in the programmer's 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 object-oriented design patterns can be made
redundant or written in a more concise way using lambda expressions. In this section, we
explore five design patterns:
Strategy
Template method
Observer
Chain of responsibility
Factory
We show how lambda expressions can provide an alternative way to solve the same problem
each design pattern is intended for.
 
Search WWH ::




Custom Search