May 19, 2015
Apply Template Method Pattern in Report ImplementationAlbert Guo
2
Agenda Introduction Template method: UML class diagram Usage Example Benefits
3
Introduction A template method defines the program skeleton of an
algorithm. One or more of the algorithm steps can be overridden by subclasses to allow differing behaviors while ensuring that the overarching algorithm is still followed.
In object-oriented programming, first a class is created that provides the basic steps of an algorithm design. These steps are implemented using abstract methods. Later on, subclasses change the abstract methods to implement real actions. Thus the general algorithm is saved in one place but the concrete steps may be changed by the subclasses.
4
Introduction – cont. Intent
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
Motivation Sometimes you want to specify the order of
operations that a method uses, but allow subclasses to provide their own implementations of some of these operations
5
Participants
CollaborationsConcreteClass relies on AbstractClass to implement the invariant steps of the algorithm.
6
Participants – cont.
Abstract class Defines abstract primitive operations that concrete subclasses
define to implement steps of an algorithm. Implements a template method defining the skeleton of an
algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
Concrete class implements the primitive operations to carry out subclass-
specific steps of the algorithm.
7
Usage Operations which must be overridden by a subclass should
be made abstract If the template method itself should not be overridden by a
subclass, it should be made final In a template method, the parent class calls the operations of
a subclass and not the other way around. This is an inverted control structure that’s sometimes referred to as "the Hollywood principle," as in, "Don't call us, we'll call you".
8
Example
9
Use Case Diagram
10
Class Diagram
Abstract primitive operations
Template method
implement primitive operations
11
Template Method Content
Get data source
Assign Jasper
Template File
Generate JasperPrint
Setup Export Format
Export Report
12
Abstract primitive operations
Template method
Abstract Class
13
extends abstract class
Implement operation in each method
Concrete Class
14Implement operation in each methodConcrete Class
15
Sequence Diagram
16
NIG135Controller
it will be executed in sequence:1. prepareDataSource2. getReportTemplateFile3. generateJasperPrint4. setupExportFormat5. exportReport
17
Benefits To make many similar operations template. From many specialized operations to a generalized
operation. Refactor common behavior to simplify code. Algorithm related improvement.