Template-Method

Template-Method design is the approach where a skeleton (class/struct) is acting as an interface placeholder while having other hidden sub-skeleton (class/struct) with the same structure supplying the underlying functionalities. Interface in Go is the best example for Template-Method Design.

A lot of large framework uses this design to facilitate flexibility.

The model diagram is as follow:

When to Use (Problem)

  1. When the problem has algorithm that consists of large definition variation and fixated part that requires customization.
  2. Common patterns among all variations are available.
  3. To control all sub classes interfaces

Example Codes (Solution)

The simplest example would be having a generalized interface to call while feeding the sub-classes into the interface for operations. This is almost similar to "duck typing" but at a definition level. Here is an example:

package main

import (
        "fmt"
)

// template
type animal interface {
        cry() string
}

// simple abstract interface for animal cry
func animalCry(a animal) {
        if a != nil {
                fmt.Println(a.cry())
        }
}



// dog sub-class
type dog struct {
}

func (a *dog) cry() string {
        return "bark"
}


// cat sub-class
type cat struct {
}

func (a *cat) cry() string {
        return "meow"
}


// human sub-class
type human struct {
}

func (a *human) cry() string {
        return "hello"
}




func main() {
        animalCry(&dog{})
        animalCry(&cat{})
        animalCry(&human{})
        animalCry(nil)
}
// Output:
// bark
// meow
// hello

Notice that all 3 animals: dog, cat and human have same primitive cry function pattern? That is due to the animal interface that unifies them. Then, animalCry uses the interface to perform the cry printout. If the sub structure is not available, animalCry will just do nothing.

Expected Outcome (Consequences)

Here are the list of consequences applying this design:

  • Reusable code
  • Unified sub-class/structure interfaces
  • Pure isolation public facing interface from private implementation
  • Higher order algorithm are not affected by lower order algorithm changes (hierarchy isolation)
  • Complicated test codes (may show a lot of test data duplication for lower order algorithms)

That's all about Template-Method design pattern.