May 09, 2021 CoffeeScript
Define the structure of an algorithm as a series of high-level steps so that the behavior of each step can be specified so that algorithms belonging to a family have the same structure but have different behaviors.
Use the template method to describe the structure of the algorithm in the parent class and authorize one or more specific sub-classes to implement it in detail.
For example, imagine that you want to simulate the generation of various types of files, each with a title and body.
class Document
produceDocument: ->
@produceHeader()
@produceBody()
produceHeader: ->
produceBody: ->
class DocWithHeader extends Document
produceHeader: ->
console.log "Producing header for DocWithHeader"
produceBody: ->
console.log "Producing body for DocWithHeader"
class DocWithoutHeader extends Document
produceBody: ->
console.log "Producing body for DocWithoutHeader"
docs = [new DocWithHeader, new DocWithoutHeader]
doc.produceDocument() for doc in docs
In this example, the algorithm describes the generation of a file in two steps: one to produce the title of the file and the other to generate the body of the file. T he parent class is an empty way to implement each step, and polymorphism enables each specific sub-class to make different use of the method by overriding the step-by-step approach. In this example, DocWithHeader implements the steps for the body and title, and DocWithOutHeader implements the steps for the body.
The generation of different types of files is a matter of simply storing document objects in an array, simply traversing each document object and calling its productDocument method.