Design Patterns Frameworks Chapter 6 Template Method by moneu

VIEWS: 32 PAGES: 29

									Design Patterns & Frameworks
   Chapter 6 – Template   Method



   Conducted By Andy LAI


                                   1
Topics – Template Method
   Introduction to Template Method
    Design Pattern
   Structure of Template Method
   Generic Class and Concrete Class
   Plotter class and Plotter Function Class



                                               2
Introduction

The DBAnimationApplet illustrates the use of an abstract class
that serves as a template for classes with shared functionality.

An abstract class contains behavior that is common to all its
subclasses. This behavior is encapsulated in nonabstract methods,
which may even be declared final to prevent any modification.
This action ensures that all subclasses will inherit the same
common behavior and its implementation.

The abstract methods in such templates ensure the interface of the
subclasses and require that context specific behavior be
implemented for each concrete subclass.
                                                                     3
Hook Method and Template Method
The abstract method paintFrame() acts as a placeholder for the
behavior that is implemented differently for each specific context.

We call such methods, hook methods, upon which context specific
behavior may be hung, or implemented.

The paintFrame() hook is placed within the method update(),
which is common to all concrete animation applets. Methods
containing hooks are called template methods.



                                                                      4
Hook Method and Template Method (Con’t)

The abstract method paintFrame() represents the behavior
that is changeable, and its implementation is deferred to the
concrete animation applets.

We call paintFrame() a hook method. Using the hook
method, we are able to define the update() method, which
represents a behavior common to all the concrete animation
applets.




                                                                5
Frozen Spots and Hot Spots

A template method uses hook methods to define a common
behavior.

Template method describes the fixed behaviors of a generic
class, which are sometimes called frozen spots.

Hook methods indicate the changeable behaviors of a
generic class, which are sometimes called hot spots.




                                                             6
Hook Method and Template Method (Con’t)

The abstract method paintFrame() represents the behavior
that is changeable, and its implementation is deferred to the
concrete animation applets.

We call paintFrame() a hook method. Using the hook
method, we are able to define the update() method, which
represents a behavior common to all the concrete animation
applets.




                                                                7
Structure of the Template Method Design Pattern


GenericClass
                          …
templateMethod()
                          hookMethod1()
hookMethod1()             …
hookMethod2()             hookMethod2()
                          …



ConcreteClass
hookMethod1()
hookMethod2()
                                                  8
Structure of the Template Method Design Pattern (Con’t)

GenericClass (e.g., DBAnimationApplet), which defines
abstract hook methods (e.g., paintFrame()) that concrete
subclasses (e.g., Bouncing-Ball2) override to implement
steps of an algorithm and implements a template method
(e.g., update()) that defines the skeleton of an algorithm by
calling the hook methods;


ConcreteClass (e.g., Bouncing-Ball2) which
implements the hook methods (e.g., paintFrame()) to
carry out subclass specific steps of the algorithm
defined in the template method.

                                                                9
Structure of the Template Method Design Pattern (Con’t)

In the Template Method design pattern, hook methods do
not have to be abstract.

The generic class may provide default implementations for
the hook methods.

Thus the subclasses have the option of overriding the hook
methods or using the default implementation.

The initAnimator() method in DBAnimationApplet is a
nonabstract hook method with a default implementation.

The init() method is another template method.
                                                             10
A Generic Function Plotter

The generic plotter should factorize all the behavior related to
drawing and leave only the definition of the function to be plotted
to its subclasses.

A concrete plotter PlotSine will be implemented to plot the function

                              y = sin x




                                                                       11
A Generic Function Plotter (con’t)
The template method pattern offers a reasonable solution.

The single-variable function to be plotted can be represented
as a hook method in the generic plotter class.

The function plotting method can then be defined in the
generic plotter classes as a template method.

The generic plotter class is outlined in the following program.




                                                                  12
 A Generic Function Plotter (con’t)

public abstract class Plotter {
 //the hook method
 public abstract double func (double x) ;

 //the template method
 protected void plotFunction (Graphics g) {
       //…func(..)…
 }
//…
}


                                              13
GenericClass and ConcreteClass

The concrete plotter will only need to extend the generic
plotter and define the function to be plotted by overriding
the hook method.




                                                              14
GenericClass and ConcreteClass (Con’t)
                              Plotter
    Applet
                          func()
                         paint()
                         plotFuction()
                         drawCoordinates()




              PlotSine                       PlotCosine
             func()                          func()

                                                          15
GenericClass and ConcreteClass(Con’t)
The generic function Plotter is implemented
as an applet. It has the following methods :

   Init()
    Initialization method to get the parameters
   Func()
    Hook method representing the function to
    be plotted

                                                  16
GenericClass and ConcreteClass(Con’t)

   paint()
    Method to paint the image
   plotFunction()
    Template method, invoked by paint() to
    plot the function
   drawCoordinate()
    Auxiliary function called by paint() to draw
    the x and y axes and tick marks.
                                                   17
 Generic Plotter Class

Plotter takes the following parameters set in the applet tag:

xorgin      The x coordinates of the origin on the canvas

yorgin     The y coordinates of the origin on the canvas

ratio       The number of pixels in the unit length on the x axis

yratio       The number of pixels in the unit length on the y axis



                                                                     18
Generic Plotter Class (Con’t)




                                19
Generic Plotter Class (Con’t)
import java.awt.*;
public abstract class Plotter
  extends java.applet.Applet {
 public abstract double func(double x);   //the hook method

public void init() {
 d = getSize();
 String att = getParameter("xratio");
 if (att != null)
   xratio = Integer.parseInt(att);
 att = getParameter("yratio");
 if (att != null)
   yratio = Integer.parseInt(att);



                                                              20
Generic Plotter Class (Con’t)

     att = getParameter("xorigin");
        if (att != null)
          xorigin = Integer.parseInt(att);
        else
          xorigin = d.width / 2;
        att = getParameter("yorigin");
        if (att != null)
          yorigin = Integer.parseInt(att);
        else
          yorigin = d.height / 2;
      }



                                             21
Generic Plotter Class (Con’t)

     public void paint(Graphics g) {
       drawCoordinates(g);
       plotFunction(g);
     }

     /** the dimension of the viewing area */
     protected Dimension d;

     /** The color used for plotting */
     protected Color color = Color.black;

     /** The position of the origin of the coordinate system */
     protected int xorigin, yorigin;

                                                                  22
Generic Plotter Class (Con’t)

  /** The number of pixels between 0 and 1 in x and y direction */
   protected int xratio = 100, yratio = 100;

   protected void plotFunction(Graphics g) { //the template method
     for (int px = 0; px < d.width; px++) {
       try {
         double x = (double)(px - xorigin) / (double)xratio;
         double y = func(x);
         int py = yorigin - (int) (y * yratio);
         g.fillOval(px - 1, py - 1, 3, 3);
       } catch (Exception e) {}
     }
   }

                                                                     23
Generic Plotter Class (Con’t)

 protected void drawCoordinates(Graphics g) {
       g.setColor(Color.white);
       g.fillRect(0, 0, d.width, d.height);

 g.setColor(color);
      g.drawLine(0, yorigin, d.width, yorigin);
 g.drawLine(xorigin, 0, xorigin, d.height);

 g.setFont(new Font("TimeRoman", Font.PLAIN, 10));
 int px, py;
 int i = 1;
        py = yorigin + 12;
        g.drawString("0", xorigin + 2, py);


                                                     24
Generic Plotter Class (Con’t)

 for (px = xorigin + xratio; px < d.width; px += xratio) {
     g.drawString(Integer.toString(i++), px - 2, py);
     g.drawLine(px, yorigin - 2, px, yorigin + 2);
   }

   i = -1;
   for (px = xorigin - xratio; px >= 0; px -= xratio) {
     g.drawString(Integer.toString(i--), px - 2, py);
     g.drawLine(px, yorigin - 2, px, yorigin + 2);
   }




                                                             25
Generic Plotter Class (Con’t)
    i = 1;
     px = xorigin + 4;
     for (py = yorigin - yratio; py >= 0; py -= yratio) {
       g.drawString(Integer.toString(i++), px, py + 4);
       g.drawLine(xorigin - 2, py, xorigin + 2, py);
     }

        i = -1;
        for (py = yorigin + yratio; py < d.height; py += yratio) {
          g.drawString(Integer.toString(i--), px, py + 4);
          g.drawLine(xorigin - 2, py, xorigin + 2, py);
        }

    }

}                                                                    26
Concrete Plotter Class
PlotSine is a concrete function plotter that simply extends the
Plotter class and implements the method func().


        public class PlotSine extends Plotter {
          public double func(double x) {
                        return Math.sin(x);
          }
        }




                                                                  27
PlotSine HTML
<!--PlotterDemo.html-->
<HTML>
<TITLE> Java Demo: Function Plotter </TITLE>
<BODY>
<H2> y = sin(x) </H2>
<APPLET CODE="PlotSine.class" WIDTH=700 HEIGHT=300>
</APPLET>
<A HREF="Plotter.java">Get the "Plotter" Source!</A>
<A HREF="PlotSine.java">Get the "PlotSine" Source!</A>
</BODY>
</HTML>


                                                     28
Question & Answer
     Session




                29

								
To top