Swift Design Patterns – Implementing the Decorator Pattern

design-patternsswift-language

I'm reading "Head first design patterns" (here you can find exact example mentioned in book)

While going through Decorator design pattern, everything was crisp and clear until I stumbled into this

They are explaining decorator using

  1. Extensions.
    I don't think extending a class through 'Extensions' results in decorator design pattern since we can't add properties to classes. As I understand, key to decorator is it ability to wraps other objects infinity, this is not possible here, although we can add functionality to existing class without inheriting it.

  2. Delegation.
    Delegation here is completely out of context. Isn't delegation itself a design pattern?

Best Answer

I think the book “Head first design patterns” is correct.

  1. As per Wikipedia, this pattern “allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class”. 'Extensions' are adding capability to an object statically and behaviors can be added by adding methods only, it may not need a new property (that is not a compulsory condition here). This stackoverflow question discussed similar stuff.

  2. Delegation can be considered as a pattern and can be utilized to add a behaviors to an existing object as per decorator pattern. Have a look on following links: https://stackoverflow.com/questions/3929996/gof-explanation-of-the-decorator-pattern-is-confusing-or-just-plain-wrong and http://lgiordani.com/blog/2014/05/19/method-overriding-in-python/

Hope it will help. Thanks.