Skip to content

Instantly share code, notes, and snippets.

@seemaullal
Last active April 23, 2017 04:54
Show Gist options
  • Save seemaullal/31de799074f037dd9584a971bd125c42 to your computer and use it in GitHub Desktop.
Save seemaullal/31de799074f037dd9584a971bd125c42 to your computer and use it in GitHub Desktop.

Template Method

Template method is pretty straight forward: you have a parent class that is pretty bare and more of a skeleton- it will mostly contain "abstract methods" that exist to be overridden by the subclasses that inherit from the parent. This allows you to put shared behavior in the parent class while letting the subclasses customize behavior by overriding methods. Let's take a look at an example:

class HotDrink
	attr_reader :temperature
	def initialize(temperature)
		@temperature = temperature
	end

	def make_drink
		raise 'Called abtract method :make_drink! Subclasses must implement this method.'
	end

	def safe_to_drink?
		temperture < 185
	end
end

class Coffee < HotDrink
	def make_drink
		hot_water = WaterBoiler.boil_water
		ground_coffee = CoffeeGrinder.grind
		PourOver.brew(water: hot_water, coffee: ground_cofeee)
	end
end

Every method that inherits from HotDrink will have access to the default safe_to_drink method, though this method could be overrideen if needed. On the other hand, since make_drink will be different for each subclass, the template class raises an error if the method is not overriden.

Ideally, there is a balance between methods that the template class implements which are used by the subclasses and "custom" methods that the subclasses will override.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment