advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorial: Encapsulating Algorithms with the Template Method Design Pattern:

The Template Method Pattern

According to the GoF book, the Template Method design pattern "defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure."

Motivation

Warning: The example that follows uses some mathematical terminology. If math isn't your strong suit, don't worry. Just gloss over any details that make you uneasy. You can skim all you want and still get the gist of the idea.

Let's say you want to calculate the area under a curve, say , from 0 to p within an application. Figure 1 is a graphical representation of this function.


Figure 1. The Plot of Curve (f)x = (sin)x

To calculate the area under a curve, you dust off your old Calculus book. After pouring through the chapter on definite integrals, you come to the following conclusions:

  • The area under the curve in Figure 1 is 2. Whew! That wasn't difficult, but...
  • Finding the areas under some other curves can be very tricky.
To help you find the areas under some curves, you use a numerical method. With a numerical method, you divide an area into smaller, more manageable chunks. Then you add up the areas of all the chunks. The chunks may not fit exactly inside the curve, so you don't always get an exact answer. But in many situations, an approximate answer is good enough.

The simplest numerical methods are the Trapezoid Rule and Simpson's Rule. Don't worry—you don't have to understand the math in order to read the rest of this article. If you're curious, the difference between these two rules is the shape of the chunks. The Trapezoidal Rule uses rectangular chunks (as in Figure 2), and Simpson's Rule uses chunks slightly curved chunks (as in Figure 3).


Figure 2. Approximating (sin)x with the Trapezoidal Rule


Figure 3. Approximating sin'x' with Simpson's Rule

(Author's Note: We offer their sincerest apologies to the estate of Thomas Simpson for mangling his rule in Figure 3. Apparently the Trapezoid's aren't happy with us either.)

The choice between Simpson's Rule and the Trapezoidal Rule depends on several factors, including the shape of the original curve, the amount of error you can tolerate, and the amount of computing time you can devote.

You can understand most of this article's Java code without knowing anything about the formulas for Simpson's Rule and the Trapezoidal Rule. But if you're interested, both Simpson's Rule and the Trapezoidal Rule make use of four basic variables. The variables are illustrated in Figure 4.


Figure 4. The variables used in applying the Trapezoidal Rule or Simpson's Rule

The formulas for the Trapezoidal Rule and Simpson's Rule are different but the procedures for applying these formulas are the same. Here's an outline that applies to both rules:

  • Call a method, getN(), to obtain the value of n, the number of intervals.
  • Call a method, getEndpoints(), to obtain the values of a and b, the endpoints for the definite integral.
  • Call a method, calcH(), to calculate the value of h, the width of each interval.
  • Call a method, calcArea(), to calculate the area under the curve according to the formula.
  • The calcArea() method uses the methods, calcXi() and calcFunction(), to assist in calculating the area under the curve.
The code in Listing 1 applies the Trapezoid Rule formula, and the code in Listing 2 applies the Simpson's Rule formula. If you're not interested in mathematical formulas, you can treat Listings 1 and 2 as black boxes. (Go ahead and ignore Listings 1 and 2. No one will be offended).

Listing 1 contains its own definitions of the basic methods (getN(), getEndpoints(), and so on). Listing 1 also contains a method named integrate() which combines calls to the basic methods and produces a numerical answer (an approximate area under a curve).

Similarly, Listing 2 contains definitions of the basic methods, and contains a big integrate() method. Hmm! Maybe we can take advantage of the similarity between Listings 1 and 2?

The client code (Listing 3) pulls everything together.

Sample output of the client code appears in the code below:

-- Numerical Integration --
Function: f(x) = sin(x)
a = 0.0
b = 3.14159265
n = 25
Trapezoid Rule: area = 1.9973674125516483
Simpson's Rule: area = 2.0000023725694533
At this point, you may be asking yourself the following questions:
  • Why is the Simpson's Rule result different from the Trapezoid Rule result?
  • Why are the methods duplicated in each of the classes?
  • Arrrgh! Why are these guys using a math example?
Notice the duplication of methods in both the TrapezoidRule and SimpsonsRule classes. Almost all of the methods in the two classes are exactly the same. The only exception is in the calcArea() method that accounts for the differences between the Trapezoid Rule and Simpson's Rule algorithms. "Don't Repeat Yourself" is a good rule of thumb in programming, but Listings 1 and 2 contain lots of repetition. Listings 1 and 2 can certainly use some improvement.

(To answer the "Arrrgh" question, we used a math example because we just happen to like math. If you've followed along with the authors in this design pattern series, you know that we always try to use practical examples. This Template Method pattern is the perfect opportunity for us to use a real math example to demonstrate a design pattern. So there!)

UML Diagram

Figure 5 shows the official UML diagram for the Template Method pattern.


Figure 5. The variables used in applying the Trapezoidal Rule or Simpson's Rule

The diagram contains two classes:

  • The AbstractClass holds the templateMethod() method which defines the algorithm for a particular task. The templateMethod() may contain abstract and concrete primitiveOperation() methods that declare abstract methods for subclasses to implement and concrete methods for subclasses to share, respectively.
  • Each ConcreteClass implements its own version of the abstract primitiveOperation() methods that were declared in AbstractClass.
Using the Template Method Design Pattern

Using Figure 5 as a guide, you can refactor Listings 1 and 2 using the UML diagram in Figure 6.


Figure 6. The variables used in applying the Trapezoidal Rule or Simpson's Rule

A new abstract base class named Integration encapsulates the methods that the Trapezoid Rule and Simpson's Rule algorithms share. The Integration class also declares any abstract methods that the two rules implement differently (see Listing 4.)

The only abstract method in Listing 4 is calcArea(). The refactored TrapezoidRule and SimpsonsRule classes (Listings 5 and 6) are subclasses from the Integration base class. These refactored TrapezoidRule and SimpsonsRule classes implement their own versions of calcArea(). They share all of the methods defined in Integration. This example declares only one abstract method, but in general the Template Method design pattern can involve any number of abstract Java methods.

The original client code in Listing 3 works with the new Template Method pattern code in Listings 4, 5, and 6. This is an excellent example of the separation of an implementation from its interface.

Click here to download the source code for this article.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Microsoft Visual Studio 2010 Showcase
 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 39
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Windows 7: From Beta to Final Code in One Year
Google Shows Off Chrome OS, Releases Source
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?
Fedora 12 Takes Aim at Linux Networking
Top Supercomputer Nearly Doubles in Speed
Fedora 12 Linux Tackles Virtualization
Apple Gives iPhone Developers App Status Tracker
Novell Sets OpenSUSE 11.2 Free

Creating Custom Export Filters for StarOffice with XSLT
WPF Wonders: Using DataTemplates
Crystal Reports Family Offers Options for Developers
Avaya Aura Session Manager video
Avaya Aura Overview video
Exploring HTML 5's Audio/Video Multimedia Support
Overriding Virtual Functions? Use C++0x Attributes to Avoid Bugs.
Understanding the Cloud Computing Security Vulnerabilities
Cisco and IBM Target a Greener World
Upgrade to Visual Studio 2010 with the Ultimate Offer

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs