© James E. McDonough 2017

James E. McDonough, Object-Oriented Design with ABAP, 10.1007/978-1-4842-2838-8_19

19. Template Method Design Pattern

James E. McDonough

(1)Pennington, New Jersey, USA

The next stop on our voyage through the Design Patterns galaxy takes us to the Template Method design pattern , another of the design patterns found in the GoF catalog. We will find this design pattern useful when we need to establish a fixed sequence of steps while allowing for some flexibility in their implementation.

Every day we encounter situations where we must perform a sequence of steps in a certain order. We put on socks before we put on shoes; we open a car door before we get into or out of a car and we close it behind us; we carefully compare food items at the market, select some to buy, pay for them, prepare a meal with them, and clean up after the meal. None of the steps in these sequences can be done in a different order. For more complicated operations, we often use some type of modeling device to help us maintain the correct sequence in which to perform a series of tasks. We often refer to these modeling devices using words such as steps, recipe, and template.

Let’s consider what is required to prepare a favorite breakfast dish enjoyed by programmers around the world: oatmeal. Here are the steps to make a single serving of piping hot oatmeal cereal using a stovetop:

  • Stovetop directions for oatmeal:

    • Gather ingredients: oats, water, salt.

    • Place water and salt into small pot.

    • Bring water to boil.

    • Stir in oats.

    • Cook over medium heat for 5 minutes, stirring occasionally.

    • Transfer oatmeal from pot to cereal bowl.

    • Stir before serving.

This process has been used for centuries; today we can prepare oatmeal using a microwave oven instead of a stovetop. The associated steps are slightly different:

  • Microwave directions for oatmeal:

    • Gather ingredients: oats, water, salt.

    • Place oats, water, and salt into microwave-safe cereal bowl.

    • Set microwave oven to cook for 3 minutes on high.

    • Start microwave oven.

    • Stir before serving.

There’s also a variation of standard oatmeal called instant oatmeal, for which the preparation is slightly different for both the stovetop and microwave alternatives:

  • Stovetop directions for instant oatmeal:

    • Gather ingredients: instant oatmeal, water, salt.

    • Place oatmeal and salt into cereal bowl.

    • Place water into small pot.

    • Bring water to boil.

    • Pour water into cereal bowl.

    • Stir before serving.

  • Microwave directions for instant oatmeal:

    • Gather ingredients: instant oatmeal, water, salt.

    • Place oatmeal, salt, and water into microwave-safe cereal bowl.

    • Set microwave oven to cook for 2 minutes on high.

    • Start microwave oven.

    • Stir before serving.

Here we see four different sets of directions for preparing a hearty oatmeal breakfast, but they all conform to the following general sequence of steps:

  • Gather oatmeal ingredients

  • Prepare oatmeal

  • Cook oatmeal

  • Serve oatmeal

Before you can enjoy oatmeal for breakfast, each of these steps needs to be completed in the order shown, but the details involved within each of these steps depends on whether or not we are using a microwave oven and whether or not we are using instant oatmeal. Accordingly, these general steps represent a template for the operations associated with preparing oatmeal, but each step affords us some flexibility in its execution.

With software we similarly encounter situations where we need certain processes to occur in a specific order, but the details of those processes are dependent upon other influencing factors. The Template Method design pattern enables us to establish the sequence of steps, yet leaves some flexibility in the details of their implementation.

Providing Flexibility While Enforcing a Specific Sequence of Operations

The Template Method design pattern is categorized by GoF with a behavioral purpose and a class scope. The intent behind this design pattern is the following:

  • Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. The Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. 1

The Template Method makes use of these participants2 working in collaboration with each other:

  1. 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.

  2. ConcreteClass: Implements the primitive operations to carry out subclass-specific steps of the algorithm.

The UML class diagram for the Template Method is shown in Figure 19-1.

A447555_1_En_19_Fig1_HTML.jpg
Figure 19-1. UML class diagram for the Template Method design pattern

Notice the primitiveOperations specified by the abstractClass are shown using an italic font, meaning they represent abstract methods that must be implemented by a subclass. Notice also the templateMethod itself is shown using a non-italic font, meaning abstractClass is also providing the implementation for it. The templateMethod is usually marked as a final method , preventing subclasses from overriding it and reordering the sequence of operations to be performed. This is how the Template Method design pattern gets its name: a method provides a template of steps describing a specific sequence of operations to be performed while leaving some flexibility for subclasses to contribute to or override the activities to be performed for a given step.

As shown in Figure 19-2, a variation on the UML class diagram for the Template Method is one where there are no abstract methods defined by the superclass; the superclass provides default implementations for the primitive operations, each of which can be extended or overridden by the subclass as necessary.3 GoF refers to them as hook operations when they contain a default implementation that does nothing.

A447555_1_En_19_Fig2_HTML.jpg
Figure 19-2. UML class diagram for the Template Method design pattern where an abstract superclass provides method implementations for primitive operations

Figure 19-3 shows how the Template Method design pattern might apply to making oatmeal for breakfast.

A447555_1_En_19_Fig3_HTML.jpg
Figure 19-3. UML class diagram for the Template Method design pattern applied to oatmeal breakfast scenario

Here we see an oatmeal class defined with public method make, protected abstract methods named prepare, cook, and serve, and a private method called gatherIngredients. Method make is the template method, invoking the other methods defined by the oatmeal class in a specific order. The subclasses stovetopStandardOatmeal and microwaveInstantOatmeal supply implementations for each of the abstract methods defined by the superclass. Whereas the subclasses control the details of what constitutes preparing, cooking, and serving oatmeal, they do not alter the sequence of these steps in any way. Indeed, this would be enforced by assigning final to the make method of the oatmeal class, thus preventing the subclasses from changing its sequence of steps.

Template Method in ABAP

The following code shows how we might implement the Template Method design pattern UML class diagram illustrated above into functioning ABAP code. Listing 19-1 shows the abstract class oatmeal.

Listing 19-1. Abstract Class oatmeal
class oatmeal definition abstract.
  public section.
    methods      : make final.
  protected section.
    data         : oats type cup
                 , water type cup
                 , salt type pinch
                 .
    methods      : prepare abstract
                 , cook abstract
                 , serve abstract
                 .
  private section.
    methods      : gather_ingredients.
endclass.
class oatmeal implementation.
  method make.
    call method me->gather_ingredients.
    call method me->prepare.
    call method me->cook.
    call method me->serve.
  endmethod.
  method gather_ingredients.
    me->oats = get oats
    me->water = get water
    me->salt = get salt
  endmethod.
endclass.

The oatmeal class shown in Listing 19-1 plays the role of the AbstractClass participant. Notice that its public method is marked as final, meaning subclasses cannot override it. Notice also that all of the protected methods are abstract, delegating implementations for them to the subclasses.

The subclass associated with making standard oatmeal using a stovetop, shown in Listing 19-2 and playing the role of the ConcreteClass participant, inherits from the oatmeal class above and provides implementations for the abstract methods defined in the superclass.

Listing 19-2. Class stovetop_standard_oatmeal
class stovetop_standard_oatmeal definition                                       inheriting from oatmeal.
  protected section.
    methods      : prepare redefinition
                 , cook    redefinition
                 , serve   redefinition
                 .
endclass.
class stovetop_standard_oatmeal implementation.
  method prepare.
    place me->water and me->salt into small pot
  endmethod.
  method cook.
    bring me->water to boil
    stir in me->oats
    cook over medium heat for 5 minutes
    stir occasionally
  endmethod.
  method serve.
    transfer oatmeal from pot to cereal bowl
    stir
  endmethod.
endclass.

The subclass associated with making instant oatmeal using a microwave, shown in Listing 19-3, also plays the role of a ConcreteClass participant, also inherits from the oatmeal class above, and also provides implementations for the abstract methods defined in the superclass.

Listing 19-3. Class microwave_instant_oatmeal
class microwave_instant_oatmeal definition inheriting from oatmeal.
  protected section.
    methods      : prepare redefinition
                 , cook    redefinition
                 , serve   redefinition
                 .
endclass.
class microwave_instant_oatmeal implementation.
  method prepare.
    place me->oats, me->water and me->salt into microwave-safe bowl
  endmethod.
  method cook.
    set microwave oven for cooking 2 minutes on high
    start microwave oven
  endmethod.
  method serve.
    stir
  endmethod.
endclass.

Compare the implementations of the abstract methods provided by both of the subclasses above. Each one implements the methods according to the constraints imposed upon it by the type of oatmeal and type of cooking device with which it is associated. Additional subclasses can be defined to handle the remaining two combinations of oatmeal type and cooking device.

A client intending to use this set of classes might provide code such as shown in Listing 19-4.

Listing 19-4. Code for Client Intending to Use the Classes Defined Above
o
o
data           : breakfast type ref to oatmeal.
o
o
if cooking_device eq 'microwave'.
  if type_of_oatmeal eq 'instant'.
    create object breakfast type microwave_instant_oatmeal.
  else.
    create object breakfast type microwave_standard_oatmeal.
  endif.
else.
  if type_of_oatmeal eq 'instant'.
    create object breakfast type stovetop_instant_oatmeal.
  else.
    create object breakfast type stovetop_standard_oatmeal.
  endif.
endif.
call method breakfast->make.
o
o

Notice in this code that once it is determined the type of class to instantiate, no subsequent conditional logic is required with the call to its make method, with the invoked instance assuming complete control over the process by which an oatmeal breakfast is made.

Summary

In this chapter, we learned how a superclass defines a fixed sequence of steps to be performed while leaving some flexibility for how those steps are facilitated by subclasses. The Template Method design pattern is characterized by a superclass that defines a public method that invokes its own protected methods in a specific order. These protected methods can be marked abstract, requiring their implementation by subclasses, or they can be fully implemented by the superclass containing processing to be performed on behalf of its subclasses, or they can be empty methods, known as hooks, which do nothing except provide a place where subclasses can override the empty method and supply extra processing to be performed. A defining characteristic of the Template Method design pattern is that subclasses have the option to override certain steps of a process but cannot override the sequence in which those steps are performed.

Template Method Exercises

Refer to Chapter 16 of the functional and technical requirements documentation (see Appendix B) for the accompanying ABAP exercise programs associated with this chapter. Take a break from reading the book at this point to reinforce what you have read by changing and executing the corresponding exercise programs. There is one exercise program associated with this chapter: ZOOT309A.

Footnotes

1 GoF, p 325.

2 GoF, p 327.

3 Technically, when no abstract methods are defined in the superclass, it loses the requirement to be regarded as an abstract class. Most likely, however, there are multiple inheritors, each extending or overriding the methods defined in the superclass, since without these subclasses to distinguish one sequence of template steps from another there would be no reason for establishing a template method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset