The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.

Post on 19-Jan-2016

224 views 0 download

Tags:

Transcript of The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.

The Template Method Pattern(Behavioral)

©SoftMoore Consulting Slide 1

Motivation

• In software development we frequently encounter a general algorithm that gets repeated with several variations for different contexts.

• The variations are often implemented using– multiway branches/conditional statements– copy-and-paste

• Problems– difficult to understand– difficult to maintain

• What if the algorithm needs to be modified?• What if we need to add a new variation?

©SoftMoore Consulting Slide 2

Motivation(continued)

• The Template Method pattern can be used to eliminate duplication and improve source code understanding and maintainability.– Identify the basic algorithm template and the different variations.– Implement the algorithm in a method that calls abstract methods

to accommodate the variations.– For each variation, create a subclass that implements the

abstract methods.

©SoftMoore Consulting Slide 3

The Template Method is a fundamental technique for code reuse.

Template Method Pattern

• 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 nature.

• Also Known As: The Hollywood Principle(“Don’t call us; we’ll call you.”)

Slide 4©SoftMoore Consulting

Template Method Pattern(continued)

Applicability: The Template Method pattern should be used

• when designing an algorithm that is potentially reusablein multiple programs. Implement the control flow and invariant parts of an algorithm in a Template Method, and leave it up to subclasses to implement the behavior that can vary.

• when common behavior among subclasses should be factored and localized in a common class to avoid code duplication.

• to control subclasses extensions. You can define a template method that calls “hook” operations at specific points, thereby permitting extensions only at those points.

Slide 5©SoftMoore Consulting

Template Method Pattern(continued)

©SoftMoore Consulting Slide 6

...primitiveOperation1()…primitiveOperation2()...

AbstractClass

templateMethod()primitiveOperation1()primitiveOperation2()

ConcreteClass

primitiveOperation1()primitiveOperation2()

Structure

Client

©SoftMoore Consulting

Template Method Pattern(continued)

Participants

• AbstractClass– 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.

• ConcreteClass– implements the primitive operations to carry out subclass-specific

steps of the algorithm.

Slide 7

Template Method Pattern(continued)

Collaborations

• ConcreteClass relies on AbstractClass to implement the invariant steps of the algorithm.

©SoftMoore Consulting Slide 8

©SoftMoore Consulting

Template Method Pattern(continued)

Consequences

• Template methods are particularly important in class libraries since they factor out common behavior in library classes.

• Template methods can call– concrete operations (in its own class other classes)– primitive operation (abstract operations)– hook operations (provide default behavior but may be

overridden)

It is important for template methods to specify which operations are hooks (may be overridden) and which are primitive (abstract operations that must be overridden).

Slide 9

©SoftMoore Consulting

Template Method Pattern(continued)

Consequences (continued)

• A parent class calls operations implemented in a subclass, and not the other way around.

Slide 10

Template Method Pattern(continued)

Implementation

• Operations that must be overridden by a subclass should be given protected access and declared as abstract (pure virtual in C++)

• In general, the template method should be not be overridden. It should be declared as final in Java (nonvirtual method in C++)

• To allow a subclass to insert optional code at a specific point in the algorithm, insert “hook” methods into the template method. These hook methods define default behavior at that point in the code, which may do nothing.

©SoftMoore Consulting Slide 11

Template Method Pattern(continued)

Implementation (continued)

• Try to minimize the number of operations that a subclass should override; otherwise using the template method becomes tedious.

• Consider adding a prefix to primitive operations; e.g., “do”

©SoftMoore Consulting Slide 12

©SoftMoore Slide 13

Template Method Pattern in Java(HTTP Servlets)

• A servlet is a small Java program that runs within a web server. Servlets support a request/response computing model that is commonly used in internet applications.

• The servlet API is a standard Java extension defined in packages– javax.servlet– javax.servlet.http

• Interface Servlet and abstract class GenericServlet define a generic, protocol-independent servlet with a general service() method.public void service(ServletRequest request, ServletResponse response)

throws ServletException, java.io.IOException;

©SoftMoore Slide 14

Template Method Pattern in Java(HTTP Servlets continued)

• Class HttpServlet implements the Servlet interface and provides support for the HTTP protocol.

• The service() method of HttpServlet dispatches the HTTP messages to one of several special methods– doGet() – doPost()– doPut() – doDelete()– doHead() – doOptions()– doTrace()

• The “template method” is actually performed by the web server to extract form parameters, create request and response objects, and call the appropriate HTTP method.

©SoftMoore Slide 15

Template Method Pattern in Java(HTTP Servlets continued)

The service() method inHttpServlet

Web Server

HttpServlet

service()

HTTPClient

doGet()doPost()doPut()doDelete()doHead()doOptions()doTrace()

©SoftMoore Slide 16

Template Method Pattern in Java(HTTP Servlets continued)

Using HttpServlet

• Create a new servlet by extending HttpServlet and overriding either doGet() or doPost(), or possibly both.

• Other methods can be overridden to get more fine-grained control.

©SoftMoore Consulting Slide 17

Template Method Pattern in Java(Example: HelloWorld Servlet)

public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter();

out.println("<html>"); out.println("<head>"); out.println(" <title>Hello</title>"); out.println("</head>"); out.println("<body>"); out.println(" <h1 align=\"center\">Hello, world.</h1>"); out.println("</body>"); out.println("</html>"); } }

Template Method Pattern in Java(JUnit)

• The early versions of JUnit used idea that there is a common structure to most tests:– set up a test fixture– run some code against the fixture and check the results– clean up the fixture

• JUnit used the template method pattern to encapsulate this structure.public void run() {     setUp();     runTest();     tearDown(); }

©SoftMoore Consulting Slide 18

Note: This is a simplified version ofthe approach originally used by JUnit.

Template Method in Java(Collection Classes)

• In package java.util, most of the non-abstract methods of AbstractList, AbstractSet, and AbstractMap implement the Template Method pattern.

• For example, the equals() method of AbstractList is implemented using other methods in the class, primarily the ListIterator. Concrete implementations of AbstractList can provide different implementations of ListIterator that will be called by the equals() method.

©SoftMoore Consulting Slide 19

Related Patterns

• Factory Methods are often called by template methods.

• Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.

©SoftMoore Consulting Slide 20

©SoftMoore Consulting

References

• Template method pattern (Wikipedia)http://en.wikipedia.org/wiki/Template_method_pattern

• Template Method Pattern (Object-Oriented Design)http://www.oodesign.com/template-method-pattern.html

• Template Method Design Pattern (SourceMaking)http://sourcemaking.com/design_patterns/template_method

Slide 21