By Neha Suwal on Nov, 29, 2016
The Template Method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
According to Gang of Four,
“Define a skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing its subclasses.”
class Animal attr_reader :type def initialize(type) @type = type end def speak if @type == :cow puts "MOOO MOOO" elsif @type == :pig puts "OINK OINK" elsif @type == :duck puts "QUACK QUACK" end end end Animal.new(:cow).speak Animal.new(:pig).speak Animal.new(:duck).speak
class Animal def speak raise NotImplementedException end end class Cow < Animal def speak puts "MOOO MOOO" end end Cow.new.speak Animal.new.speak
uninitialized constant Animal::NotImplementedException (NameError)
Factory Pattern also uses Inheritance. So, there is a chance you might confuse Template Pattern with it. Unlike Template Design pattern you leave the decision on which Subclass to use to the factory class. Think of it as Factory Method is to creating objects as Template Method is to implementing an algorithm.You can refer to the following link [Factory Design Pattern in Ruby]. I am sure. This will help you take better decisions on situations when you get confused which of these patterns to implement.
Strategy Pattern and Template Method Pattern serve very similar needs. They both allow the user to change the algorithm at run time. The basic difference is on how the implementations is carried out. It is inheritance versus aggregation (is-a versus has-a). With Strategy pattern the algorithm is encapsulated inside the implementing sub class.
You use Strategy Pattern when you need to change the algorithm of a specific method. Whereas, Template Method Pattern is used when you want to some changes( not all ) in the behaviours of the class.
Don't miss the next one!