Java Reference
In-Depth Information
NOTE
In some respects, trying to squeeze a lot of code into one method leads to poor readability
is the golden rule governing how to apply lambda expressions. The only reason I haven't
pushed this so much is that it's also the golden rule of writing normal methods!
Template Method Pattern
A pretty common situation when developing software is having a common algorithm with a
set of differing specifics. We want to require the different implementations to have a com-
mon pattern in order to ensure that they're following the same algorithm and also to make
the code easier to understand. Once you understand the overall pattern, you can more easily
understand each implementation.
The template method pattern is designed for these kinds of situations. Your overall algorithm
design is represented by an abstract class . This has a series of abstract methods that repres-
ent customized steps in the algorithm, while any common code can be kept in this class.
Each variant of the algorithm is implemented by a concrete class that overrides the abstract
methods and provides the relevant implementation.
Let's think through a scenario in order to make this clearer. As a bank, we're going to be giv-
ing out loans to members of the public, companies, and employees. These categories have a
fairly similar loan application process—you check the identity, credit history, and income
history. You get this information from different sources and apply different criteria. For ex-
ample, you might check the identity of a person by looking at an existing bill to her house,
but companies have an official registrar such as the SEC in the US or Companies House in
the UK.
We can start to model this in code with an abstract LoanApplication class that controls the
algorithmic structure and holds common code for reporting the findings of the loan applica-
tion. There are then concrete subclasses for each of our different categories of applicant:
CompanyLoanApplication , PersonalLoanApplication , and EmployeeLoanApplication .
Example 8-21 shows what our LoanApplication class would look like.
Example 8-21. The process of applying for a loan using the template method pattern
public
public abstract
abstract class
class LoanApplication
LoanApplication {
public
public void
void checkLoanApplication () throws
throws ApplicationDenied {
checkIdentity ();
Search WWH ::




Custom Search