Template Method Pattern

The Template Method Pattern consists of a method that is used as a default value. It is then overwritten in classes that inherit or include it:

class Bicycle
  attr_reader :size, :chain, :tire_size

  def initialize(args={})
    @size = args[:size]
    @chain = args[:chain] || default_chain
    @tire_size = args[:tire_size] || default_tire_size
  end

  def default_chain # <- common default
    '10-speed'
  end
end

This way classes that inherit from Cycle can overwrite default_chain, removing the need of super calls and achieve less coupling:

</pre>
class MountainBike < Bicycle
  def default_chain
    '5-speed'
  end
end

Seen in POODR.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s