Template Method Pattern - CoffeeScript Design Patterns

By on

The Template Method pattern just defines a set of methods and the order in which they should be executed. It’s pretty basic.

# * Defines abstract **primitive operations** that concrete  
#   subclasses define to implement steps of an algorithm.  
# * Implements a template method defining the skeleton of  
#   an algorithm. The template method calls primitive  
#   operations as well as operations defined in AbstractClass  
#   or those of other objects.  
class AbstractClass  
  templateMethod: ->  
    @primitiveOperation1()  
    @primitiveOperation2()

  primitiveOperation1: ->
  primitiveOperation2: -> 

# 1. Implements the primitive operations to carry out subclass
# 2. specific steps of the algorithm.

class ConcreteClass extends AbstractClass  
  primitiveOperation1: ->  
    console.log "primitiveOperation1"  
  primitiveOperation2: ->  
    console.log "primitiveOperation2"  

Usage:

concrete = new ConcreteClass()  
concrete.templateMethod()  

I usually like to make the template method a static method that instantiates the class and runs the other methods. That way there’s no way to fuck it up.

# * Abstract class with static template method  
# * Instantiates the class and calls its methods  
class AbstractClass  
  @templateMethod: ->  
    cls = new @()  
    cls.primitiveOperation1()  
    cls.primitiveOperation2()  
  primitiveOperation1: ->  
  primitiveOperation2: ->

class ConcreteClass extends AbstractClass  
  primitiveOperation1: ->  
    console.log "primitiveOperation1"  
  primitiveOperation2: ->  
    console.log "primitiveOperation2"  

Usage:

ConcreteClass.templateMethod()