Java Reference
In-Depth Information
8.2.2. Template method
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. Okay, it
sounds a bit abstract. In other words, the template method pattern is useful when you find
yourself in a situation such as “I'd love to use this algorithm but I need to change a few lines so it
does what I want.”
Let's 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
customer's details from the bank database and finally does something to make the customer
happy. Different online banking applications for different banking branches may have different
ways of making a customer happy (for example, adding a bonus on their account or just sending
them 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 its ID and then make the customer happy. Different branches can now provide
different implementations of the method makeCustomerHappy by subclassing the
OnlineBanking class.
Using lambda expressions
You can tackle the same problem (creating an outline of an algorithm and letting implementers
plug in some parts) using your favorite lambdas! The different components of the algorithms
you want to plug in can be represented by lambda expressions or method references.
 
Search WWH ::




Custom Search