chapter eight

8 The Template Method and Strategy Design Patterns

 

This chapter covers

  • The Template Method Design Pattern
  • The Strategy Design Pattern

Each design pattern is an industry-proven model from which we can create a well-designed solution to a common software architecture problem. A design pattern is only a model because it is rarely a solution we can use directly — we use it as the basis to create a custom solution to an architecture problem in our application. This chapter covers two design patterns.

Application development, and programming in general, are about algorithms and data. The data are the ingredients, and the algorithms are the steps of the recipe. The two design patterns in this chapter, the Template Method Design Pattern and the Strategy Design Pattern, are models for a software architecture that must manage multiple algorithms.

Our example application for the Template Method Design Pattern generates reports about sports. The basic outline of the reports is the same, but parts of the report differ. The example application for the Strategy Design Pattern shows how it can deploy strategies to recruit players and reserve venues for different sports. The strategies are interchangeable, and the application can determine at run time which one to deploy depending on the sport.

For each of the two patterns, we’ll have example code that doesn’t use the pattern, followed by example code modeled by the pattern, and then we’ll see the improvement the pattern makes.

8.1 The Template Method Design Pattern defines the steps of an algorithm

8.1.1 Desired design features

8.1.2 Before using Template Method

8.1.3 After using Template Method

8.1.4 Template Method’s generic model

8.2 The Strategy Design Pattern encapsulates algorithms

8.2.1 Desired design features

8.2.2 Before using Strategy

8.2.3 After using Strategy

8.2.4 Strategy's generic model

8.3 Choose between Template Method and Strategy

8.4 Summary