Decorator Pattern

suggest change

Decorator pattern adds behavior to objects without affecting other objects of the same class. The decorator pattern is a useful alternative to creating sub-classes.

Create a module for each decorator. This approach is more flexible than inheritance because you can mix and match responsibilities in more combinations. Additionally, because the transparency allows decorators to be nested recursively, it allows for an unlimited number of responsibilities.

Assume the Pizza class has a cost method that returns 300:

class Pizza
  def cost
    300
  end
end

Represent pizza with an added layer of cheese burst and the cost goes up by 50. The simplest approach is to create a PizzaWithCheese subclass that returns 350 in the cost method.

class PizzaWithCheese < Pizza
  def cost
    350
  end
end

Next, we need to represent a large pizza that adds 100 to the cost of a normal pizza. We can represent this using a LargePizza subclass of Pizza.

class LargePizza < Pizza
  def cost
    400
  end
end

We could also have an ExtraLargePizza that adds a further 15 to LargePizza. If each size could also be served with cheese, we would need LargePizzaWithCheese and ExtraLargePizzaWithCheese as well. That is 6 classes.

To simplify, use modules to add behavior to one Pizza object:

Modules, extend, and super:

class Pizza
  def cost
    300
  end
end

module CheesePizza
  def cost
    super + 50
  end
end

module LargePizza
  def cost
    super + 100
  end
end

pizza = Pizza.new         # cost is 300
pizza.extend(CheesePizza) # cost is 350; extend returns pizza, not the cost
pizza.extend(LargePizza)  # cost is 450
pizza.cost                #=> 450

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents