mercredi 13 juillet 2022

Why send messages from the superclass to get specialisations in the template method pattern?

I've been reading Sandi Metz's book on OOP in Ruby. In the chapter on inheritance there is a section on the template method pattern.

It talks about having a base class with common behaviour, then subclasses that inherit this behaviour and implement their own specialised interfaces as needed.

The book goes on to discuss how to send messages from the base class to the subclass methods to get the specific behaviour and override defaults, like so:

class Bicycle
  attr_reader :size, :chain, :tire_size

  def initialize(**opts)
    @size = opts[:size]
    @chain = opts[:chain] || default_chain
    @tire_size = opts[:tire_size] || default_tire_size
  end

  def default_chain
    "11-speed"
  end

  def default_tire_size
    raise NotImplementedError
  end
end

class RoadBike < Bicycle
  def default_tire_size
    "23"
  end
end

What is the benefit of getting the base class to make this call to a method in a sub class, if the method can be defined in the subclass itself?

Aucun commentaire:

Enregistrer un commentaire