The Template Method Pattern – Override Strategy Logic

The first time I looked at the Strategy pattern it was love at first sight. The pattern’s logic seemed to be a mythical panacea come true, where the use of Composition over Inheritance not only was exploited to its fullest, but the implementation was so clean and elegant that its charming influence was hard to resist. What could be more seductive than passing a few implementers of a given contract into one or more consumers allowing them to digest different algorithms at runtime through the reins of Polymorphism?

Of course, when I started coding strategies the magic of that “first date” vanished. I realized that some of my strategy classes barely carried state, or even worse, shared extensive chunks of duplicated implementations with each other, all smelly symptoms of a bad design.

In hindsight, this clever quote from C. S. Lewis, sums up a valuable lesson for me: “Experience is the most brutal of teachers.” The first tough lesson I learned from working with strategy classes is that sooner or later they tend to suffer of stateless issues rooted in the pattern’s intrinsic nature, and unfortunately they can’t be sorted out without drastic refactoring techniques.

While dealing with a few stateless issues here and there is something I can stand, even at the expense of being blamed for writing procedural code inside of class constructs, things are radically different when the same logic appears across multiple classes. This facet has nothing to do with the pattern’s essence or with some other tangled reason… it’s simply a nasty consequence of clunky design, many times caused by reluctance to walk Inheritance’s path.

This bring us back to the question whether it’s feasible to eliminate duplicated strategy logic via Inheritance rather than switching over to plain Composition. Indeed it is, and the clean up process can be conducted through an ubiquitous pattern known as Template Method design pattern.

Despite the flourishy name, the logic behind the Template Method pattern is ridiculously easy to assimilate. Simply put, there’s a base class (usually an abstract one), which declares a concrete method (a.k.a. the template) responsible for outlining the steps or hooks of a certain algorithm. Most of the time the base type provides boilerplate implementation for some of those steps and the remaining ones are delegated to subclasses. In turn, the subtypes override the unimplemented steps and provide their own implementations, this way creating distilled versions of the algorithm while shared implementation is neatly preserved inside the base class.

Beyond its simple nature, Template Method does prove that Inheritance can be a powerful approach when it comes to reusing common chunks of strategy logic. In this article I’ll be demonstrating some conrete examples to show how to use the pattern’s forces for programmatically rendering some basic jQuery-based image sliders.

Building a jQuery-Based Image Slider

Even though template methods have a prolific presence in several frameworks that provide partial implementations for a given component while letting subtypes override abstract methods according to more refined and specific needs, it’s rather difficult to find examples on the Internet that showcase how to exploit the pattern’s functionality in realistic use cases. By no means do I intend to fill this gap, as it can be filled better by someone else. My goal here is merely to illustrate how to employ the pattern in the generation of markup segments that must cling to a given sequence. A nice example of this is the rendering of a jQuery-driven image slider, whose “underlying strategy algorithm” could be, with some subtle slants of course, dissected into the following steps:

  • Render the target images inside a block-level element, hooked up to an “id” or “class” attribute.
  • Include jQuery.
  • Include the slider’s jQuery plug-in.
  • Render the JavaScript that gets the slider up and running.

With these generic steps outlined, it should be pretty easy to create a base abstract class and drop into it a template method that implements partially some of these steps while delegating the implementation of the remaining ones to a few subclasses. To keep things concise, the plug-in that I’m going to use in pursuit of my didactical cause will be the nifty Cycle.

Here’s how the aforementioned base class would look like:

<?php
namespace LibraryViewHelper;

abstract class AbstractCycleSlider
{
    protected $images = array();
    
    public function __construct(array $images) {
        if (empty($images)) {
            throw new InvalidArgumentException(
                "No images were supplied.");
        }
        foreach ($images as $image) {
            $extension = pathinfo($image, PATHINFO_EXTENSION);
            if (!in_array($extension, array("gif", "jpg", "png"))) {
                throw new OutOfRangeException(
                    "Only GIF/JPG/PNG files are allowed.");
            }
        }
        $this->images = $images;
    }
    
    // Hook method for rendering the target images
    protected function renderImages() {
        $output = '<div id="slider">';
        foreach ($this->images as $image) {
            $output .= '<img src="' . $image . '">';
        }
        $output .= "</div>";
        return $output;
    }
    
    // Hook method for including jQuery and the Cycle plug-in
    protected function renderLibraries() {
        return <<<ENDHTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js></script>
ENDHTML;
    }
    
    // Hook method for rendering a transition effect (overridden by
    // subclasses)
    abstract protected function renderEffect();
    
    // Template method for rendering the slider
    public final function render() {
        return $this->renderImages()
            . $this->renderLibraries()
            . $this->renderEffect();
    }
}

The only responsibility of the AbstractCycleSlider class is to provide implementation for some of the steps required for rendering an elemental Cycle-based slider. The whole rendering sequence is in this case defined by the render() method which effectively acts as the actual “template” for the steps in question.

The class does a decent work encapsulating common strategy logic behind its slim API, sure, but on its own it’s not very useful. But let’s no rush to pass judgment just yet, though, because the functionality the template method pattern offers rests on the benefits provided by a hierarchical structure where subtypes are responsible for providing strategy logic the base type can’t supply by default.

If you scan through AbstractCycleSlider, you’ll see here’s exactly where the renderEffect() method comes into play which should be implemented down the line by one or more subclasses, that way generating disparate –yet functional–versions of the base slider.

Refined Implementations of the Base Slider

Creating a few working Cycle-driven sliders is a pretty straightforward process that boils down to subclassing the base AbstractCycleSlider and then supplying concrete implementations for its renderEffect() method.

The following subclasses do precisely that:

<?php
namespace LibraryViewHelper;

class FadeSlider extends AbstractCycleSlider
{
    protected function renderEffect() {
        return <<<ENDHTML
<script>
jQuery(document).ready(function () {
    jQuery("#slider").cycle({fx: "fade"});
});
</script>
ENDHTML;
    }
}
<?php
namespace LibraryViewHelper;

class ScrollSlider extends AbstractCycleSlider
{
    protected function renderEffect() {
        return <<<ENDHTML
<script>
jQuery(document).ready(function () {
    jQuery("#slider").cycle({fx: "scrollDown"});
});
</script>
ENDHTML;
    }
}

The implementation of the renderEffect() method provided by the above subclasses is rendering some JavaScript snippets charged with generating a couple of transition effects (Fade and Scroll) bundled with the Cycle plug-in. This shows how to delegate the implementation of strategy logic defined in a template method to a few subtypes.

If you want to put the subclasses to work, arm yourself with a nice set of sample images and try out the following:

<?php
use LibraryLoaderAutoloader,
    LibraryViewHelperFadeSlider,
    LibraryViewHelperScrollSlider;
    
require_once __DIR__ . "/Library/Loader/Autoloader.php";
$autoloader = new Autoloader();
$autoloader->register();

$images = array(
    "sample_image1.jpg",
    "sample_image2.jpg",
    "sample_image3.jpg",
    "sample_image4.jpg",
    "sample_image5.jpg"
}; 

$slider = new FadeSlider($images);
echo $slider->render();

If all goes as expected, the above script should render a nifty image slider where the target images are looped by using a soft fade-in/out transition effect.

If you change your mind and want to set up a fancy scrolling slider instead, just create an instance of the ScrollSlider class instead of its counterpart FadeSlider. Consuming the existing sliders, or eventually creating a few new ones, boils down to just providing custom implementations for the renderEffect() method.

The bad news, on the flip side, is that each slider class will be nothing but a subtle variation of the others, meaning that renderEffect() will always get its ecosystem polluted with duplicated code.

This doesn’t mean that using the template method design pattern is a bad thing at all. It’s just that in this case the custom implementations of it are way too similar to each other because we’re dealing with the same jQuery plug-in each time! The whole design would be a lot more efficient if we appealed to the pattern for rendering sliders based on different plugins as well.

Working with Different Plug-Ins

To recreate the above situation, say we want to render two disparate i1mage sliders: the first one would use the already familiar Cycle, and the second one would use Orbit. In that case, we should first refactor the earlier AbstractCycleSlider class to define a more granular template method:

<?php
namespace LibraryViewHelper;

abstract class AbstractSlider
{
    protected $images = array();
    
    public function __construct(array $images) {
        // the same constructor implementation
    }
    
    // Hook method for rendering the target images
    protected function renderImages() {
        $output = '<div id="slider">';
        foreach ($this->images as $image) {
            $output .= '<img src="' . $image . '">';
        }
        $output .= "</div>";
        return $output;
    }

    // Hook method for including jQuery
    protected function renderjQuery() {
        return <<<ENDHTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
ENDHTML;
    }

    // Hook method for including the slider's dependencies
    // (overridden by subclasses)
    abstract protected function renderDependencies();

    // Hook method for rendering a sliding effect (overridden by
    // subclasses)
    abstract protected function renderEffect();
    
    // Template method for rendering the slider
    public final function render() {
        return $this->renderImages()
            . $this->renderjQuery()
            . $this->renderDependencies()    
            . $this->renderEffect();
    }
}

This definitely looks better. Since the render() method now has been dissected into more atomic, finer-grained steps, it’s simple to create refined implementations of it.

The below subclass is a basic wrapper for a Cycle-based slider:

<?php
namespace LibraryViewHelper;

class Cycle extends AbstractSlider
{
    protected function renderDependencies() {
        return <<<ENDHTML
<script src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js">
</script>
ENDHTML;
    }

    protected function renderEffect() {
        return <<<ENDHTML
<script>
jQuery(document).ready(function () {
    jQuery("#slider").cycle({fx: "fade"});
});
</script>
ENDHTML;
    }
}

And this one brings to life an Orbit-based slider:

<?php
namespace LibraryViewHelper;

class Orbit extends AbstractSlider
{
    protected function renderDependencies() {
        return <<<ENDHTML
<link rel="stylesheet" href="/public/css/orbit.css">
<script src="/public/js/orbit.min.js">
</script>
ENDHTML;
    }

    protected function renderEffect() {
        return <<<ENDHTML
<script>
jQuery(document).ready(function () {
    jQuery("#slider").orbit();
});
</script>
ENDHTML;
    }
}

Now with these subtypes providing custom implementations for the renderDependencies() and renderEffect() methods, each plug-in can be independently rendered to the browser via a script like this:

<?php
$orbit = new Orbit($images);
echo $orbit->render();

$cycle = new Cycle($images);
echo $cycle->render();

I’m not necessarily an active proponent of this approach for adding a layer of behavior to your HTML documents, although it is neat and unobtrusive, because the process is a lot more cumbersome than just parsing a few templates hooked up to a view class or something like that. Still, it shows in a nutshell what’s actually under the hood of the Template Method pattern and how to exploit its niceties in the implementation of a few customizable view helpers.

Closing Remarks

Saying that strategy logic has been traditionally implemented and consumed through Composition isn’t breaking news. Providing consumers with a set of independent polymorphic algorithms that adhere to the formalities of a given contract makes this path a very tempting one to travel, which additionally doesn’t expose the typical oddities raised by the base type/subtype paradigm.

But on the flip side, the implementation of Inheritance-based solutions, such as the one provided by the Template Method pattern, can be effective when the steps of a certain algorithm should be selectively overridden by subtypes while keeping common strategy logic safely encapsulated in a base type.

Starting a flame war over which pattern fits the bill best doesn’t make much sense at all; just make sure to pick the one you feel gets along best with your needs at hand.

Image via Fotolia

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • Jonathan

    Where can I find the source for the LibraryLoaderAutoloader class?

    • Alex Gervasio

      Hey Jonathan,
      In fact, the PSR-0 autoloader I’m using throughout the examples is just a slimmed version of Symfony Universal Class Loader. There’s plenty of autoloaders you can pick up in the wild. However, Symfony’s is quite a nice structure that can be tweaked without much fuss. You may want to take a look at its source code here https://github.com/symfony/ClassLoader/blob/master/UniversalClassLoader.php
      Thanks for the feedback.

  • Evgeni Ivanov

    Another great article!
    I am working with PHP for several years now and just started to learn about JEE in order to get a better understanding of Martin Fowler’s Patterns of Enterpririse Application Architecture.But with the articles that you post here the process is much more easier.Thanks!

    • Alex Gervasio

      Hey Evgeni,
      Thanks for the kind compliments indeed. Glad the articles have been of some help for getting an in-depth understanding of several language-agnostic concepts and patterns. Keep up the good work :)

  • Uncle Fred

    Love your approach: present a genuinely complex problem, empower reader with a “Can do” attitude, using the expert knowledge break it down to understandable components, and tell the reader “look you solved it yourself and it wasn’t that hard!”. While giving me the in-depth knowledge, your articles fill me with a sense of achievement.
    The practical examples are super great. Would love to see an example of stateless issues you talk about here when you say “.. they tend to suffer of stateless issues rooted in the pattern’s intrinsic nature .. ” and “While dealing with a few stateless issues here and there.. ”.

    • Alex Gervasio

      Hey Fred,
      Well, Thanks for the all kind compliments indeed. It’s always nice to see more and more developers digging deeper into the nuts and bolts of some popular programming principles and patterns, which without falling down in a dogmatic attitude (the so-called patternitis), certainly can help to build up more robust and extendable software. I tried to humbly demonstrate a pinch of that in this article, and honestly I’m pretty satisfied with the feedback, even if the topic isn’t exactly what I call “trendy”.
      Regarding your question, I’m not saying the entirety of the strategy classes out there are plain stateless, because claiming that would be actually nothing but a biased, pretty pointless opinion. Even though, most of the algorithms packaged in the form of polymorphic strategies (AKA encapsulating the concept that varies) tend to be effectively stateless. If you want to put your hands on a concrete example that shows why I’m saying this, feel free to check the serializer I wrote for this post http://phpmaster.com/managing-class-dependencies-1/.
      Is this one stateless? You bet. From top to bottom. Unquestionably it does its thing pretty decently, but none of its methods mutates the class’ state. By the way, I could go even further and point you to a few more examples, but proving the concept with my own sins is a sort of beneficial mea culpa that definitively makes me feel better :) Thanks for the feedback.

  • http://alexfraundorf.com Alex Fraundorf

    Alex,
    Great article as always.
    I think you did a wonderful job explaining this pattern in a way that will appeal to experienced developers as well as those just venturing into OOP.
    I think that the Template/Overriding pattern is one that a lot of people new to OOP can quickly grasp (probably since the same basic concept is used in CSS), possibly without realizing that they are using a pattern at all.
    Thanks for the article!

    • Alex Gervasio

      Hey Alex,
      Glad you found the article to be instructive. I liked specially the point you raised with reference to using the pattern in CSS. Definitively a clever contribution, which some readers hopefully will find particularly juicy :)