Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrappers & Subclasses

 
Nidhi Sar
Ranch Hand
Posts: 252
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Feeling a little confused about wrappers - about what their purpose is.

Quoting from HFSJ:

"The Decorator/Wrapper decorates/wraps one kind of an object with an "enhanced" implementation. And by "enhanced", we mean "adds new capabilities" while still doing everything the original wrapped thing did."

Ok, so isn't that exactly what extending the class is - when you extend a class, the new class does everthing the original class did and adds new capabilities. So how is a wrapper object different from a subclass object?
 
Piotr Nowicki
Ranch Hand
Posts: 611
1
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main difference is about WHEN you add these new capabilities.

Using inheritance, you do it during compilation time (A extends B).
Using the decorator pattern, you do it during runtime (new BufferedReader(...)).

The wrapping/decorating is therefore more flexible, as you can change (add) the behavior dynamically.

Edit: oh, and remember about situations when you just can't extend some class and you still wish to add some new features to it.
 
Frits Walraven
Creator of Enthuware JWS+ V6
Saloon Keeper
Pie
Posts: 2445
96
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nidhi,

Everything that Pedro says is true.

and the obvious difference with inheritence is:
DecoratorOfA has a A

The decorator class has an instance variable of A, and maybe other instance variables and methods to add new features to A.

Regards,
Frits
 
Nidhi Sar
Ranch Hand
Posts: 252
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys, that makes it much clearer.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic