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
-
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. -
Delegation.
Delegation here is completely out of context. Isn’t delegation itself a design pattern?
1
I think the book “Head first design patterns” is correct.
-
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.
-
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.
0
You can’t add stored properties, but you can add computed properties. A computed property can act just like a stored property. In fact ObjC provides a handy set of calls to make that if not actually easy…well, at least not hard.
Performance might not be where you want it, but if performance is a big deal let the profiler tell you when you should give up on “pattern implementation purity ” and move some properties into the class proper.
You cannot directly add attributes and methods in a class, but you can do that in the decorator. Since a decorator is a composition of its supertype, you can state that the decorator is a basic object, with additional methods and attributes. Exactly like a sub-class is its super-class, with additional or modified methods and attributes.
In typical decorator, a part of the behaviour is simply identical to what is defined in the associated basic object. So you implement the methods reifying this behaviour by simply call the same method in the associated object. That’s why you can say that the Decorator Design Pattern can be used as a delegation mechanism.
It is relatively common to find (a part of) a pattern in an other one. You could for instance consider the decorator as a special kind of proxy.