Java Magazine, Nov/Dec 2016
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 57 new to java s matches a z System out println v4 validate bbbb As you can see lambda expressions remove the boilerplate code inherent in the strategy design pattern If you think about it lambda expressions encapsulate a piece of code or strategy which is what the strategy design pattern was created for so we recommend that you use lambda expressions instead for similar problems Template Method Pattern The template method design pattern is a common solution when you need to represent the outline of an algorithm and have the additional flexibility to change certain parts of it In other words the template method pattern is useful when you find yourself in a situation such as Id love to use this algorithm but I need to change a few lines so it does what I want Lets look at an example of how this pattern works Say you need to write a simple online banking application Users typically enter a customer ID and then the application fetches the customers details from the bank database and finally does something to make the customer happy Different online banking applications for diferent banking branches may have diferent ways of making a customer happy for example adding a bonus on the account or just sending less paperwork You can write the following abstract class to represent the online banking application abstract class OnlineBanking public void processCustomer int id Customer c Database getCustomerWithId id makeCustomerHappy c abstract void makeCustomerHappy Customer c The processCustomer method provides a sketch for the online banking algorithm fetch the customer given his or her ID and then make the customer happy Diferent branches can now provide different implementations of the method makeCustomerHappy by subclassing the OnlineBanking class You can tackle the same problem creating an outline of an algorithm and letting implementers plug in some parts using your favorite lambdas The diferent components of the algorithms you want to plug in can be represented by lambda expressions or method references Here we introduce a second argument to the method processCustomer of type Consumer Customer because it matches the signature of the method makeCustomerHappy defined earlier public void processCustomer int id Consumer Customer makeCustomerHappy Customer c Database getCustomerWithId id makeCustomerHappy accept c You can now plug in different behaviors directly without subclassing the OnlineBanking class by passing lambda expressions new OnlineBankingLambda processCustomer 1337 Customer c System out println Hello c getName This is another example of how lambda expressions can help you remove the boilerplate inherent in design patterns
You must have JavaScript enabled to view digital editions.