Simplest explanation I’ve heard of the decorator pattern is it’s “used to extend the functionality of a single object without affecting any other instances of the same class.” The decorator pattern is used to achieving a separation of concerns and is essential tool in the Open/Closed principle.
Here is an example:
require 'delegate'
class Person
def speak
'hello'
end
def age
30
end
end
class LatinDecorator < SimpleDelegator
# modifies existing functionality
def speak
"'hola' means '#{__getobj__.speak}'"
end
# adds new functionality
def dance
'cha-cha-cha'
end
end
person = Person.new
wrapper = LatinDecorator.new(person)
wrapper.speak # => "'hola' means 'hello'"
wrapper.age # => 30
wrapper.dance # => 'cha-cha-cha'
Most of the information from this blog post came from this blog post. Writing it in my own blog post helps me reference and learn it a bit faster.
Use the decorator pattern when you wish to extend the behavior of a single instance. If you need to extend the behavior of more instances either add methods to the class or include a modules behavior.
Stay connected