Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorator pattern vs List

While reading on Decorator pattern, came across something that needed to be clarified. In decorator pattern we just wrap a given object and used a chain of executions for calculation. But why can't we have a list of those objects and iterate through each. I mean without having the chain, can't we just use a list and simple iteration through each object ?

Thanks

like image 943
Prasad Weera Avatar asked Jul 23 '12 00:07

Prasad Weera


2 Answers

I believe you have missed the point of Decorator.

Decorator aims to add behavior transparently. The classic example is InputStream in Java. You can chain like buffering, gzip feature to an input stream. However, the "user" of that decorated input stream do not need to know there is extra behavior added. The user simply use that decorated stream as a normal stream. Of course it will work if you have each "behavior" as a separate object, and store the chain as another list and invoke them explicitly and separately. However it lost the "transparency" in decorator.

like image 140
Adrian Shum Avatar answered Sep 21 '22 06:09

Adrian Shum


With a list, you need some object to manage the list and to traverse and apply the objects. To be plug-compatible, the manager object has to be a subclass of the (usually abstract) base class of all the objects. It's just less flexible than having each object know what it's wrapping and that's it.

like image 27
Ted Hopp Avatar answered Sep 19 '22 06:09

Ted Hopp