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:
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 mainimport ( "fmt")// templatetype animal interface { cry() string}// simple abstract interface for animal cryfunc animalCry(a animal) { if a != nil { fmt.Println(a.cry()) }}// dog sub-classtype dog struct {}func (a *dog) cry() string { return "bark"}// cat sub-classtype cat struct {}func (a *cat) cry() string { return "meow"}// human sub-classtype human struct {}func (a *human) cry() string { return "hello"}func main() { animalCry(&dog{}) animalCry(&cat{}) animalCry(&human{}) animalCry(nil)}// Output:// bark// meow// helloNotice 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.
Here are the list of consequences applying this design:
That's all about Template-Method design pattern.