aspose file tools*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Decorator Pattern Vs Inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Decorator Pattern Vs Inheritance" Watch "Decorator Pattern Vs Inheritance" New topic
Author

Decorator Pattern Vs Inheritance

Shankar sanjay
Ranch Hand

Joined: Sep 14, 2009
Posts: 117
Hi,

Can anyone please tell that How Decorator pattern differs from Inheritance?, for me Decorator Pattern looks like inheritance concept.

Regards,

Sankar. S
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1773
    
    7

The decorator pattern allows you to add behaviour dynamically at runtime to an instance of a particular class, whereas inheritance adds behaviour at compile time.
You can make use of inheritance when applying the decorator pattern, although that's not always a necessity.
So it's perfectly ok to use both inheritance and composition when creating a decorator class, if you don't have a common interface you can implement.
Or if you want to create an (abstract) "base" decorator class.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

Jelle Klap wrote:
You can make use of inheritance when applying the decorator pattern, although that's not always a necessity.

Adding new behavior to the base class by creating separate subclass for every possible combination could let to a maintenance nightmare. There are better alternative available to Inheritance.


http://muhammadkhojaye.blogspot.com/
 
Consider Paul's rocket mass heater.
 
subject: Decorator Pattern Vs Inheritance