Avatar of Jay Roy
Jay RoyFlag for United States of America

asked on 

inheritance or decorator pattern

one of the question asked today in interview was how does Inheritance differ from
using decorator pattern?
I said inheritance is adding behaviour during compile time v/s decorator adds behaviour to object at runtime. The interviewer wasnt satisfied. she was hinting more towards what is the drawback of inheritance which makes decorator pattern better? or are they very similar or same?

your take?

thx
Java

Avatar of undefined
Last Comment
Jay Roy
SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of for_yan
for_yan
Flag of United States of America image


http://www.patternsforphp.org/doku.php?id=decorator
This is a good discussion of all aspects of these, based on PHP, not java, but in such general discussions it does not  matter much

Altering the behaviour of objects is a tricky business. In many cases you do not wish to alter the original object but rather tack on additional or modified behaviours. The easiest way to achieve this is using inheritance. Creating a series of subclasses allows a programmer to add additional methods and properties or alter those which already exist in the parent class. Unfortunately, as other Design Patterns often point out, inheritance can be a path full of pitfalls and traps for the unwary. The more layers exist in a class hierarchy, the more cumbersome and difficult to manage the whole structure becomes.

If we decide to set a goal of maintaining the original class as is and of disallowing any further inheritance, we immediately gain some measure of control. By preventing further inheritance we have a smaller discrete unit perfect for reuse in other projects minus the specific modifications current circumstances might require. To extend the original class and add new or modified behaviour to it we can use the Decorator Pattern.

The Decorator Pattern creates a separate class family which adds extended behaviour to an existing class while leaving the existing class unchanged. As the class is ported for reuse, we can transparently add new Decorators specific to each new application as we see fit. Additionally, since the Decorator classes are in a separate hierarchy they have a variable type which is distinct from the original class, i.e. we can tell if a class is a Decorator.

Of course the Decorator Pattern is not a silver bullet. Inheritance remains the simplest option and the Decorator Pattern is not suitable for all scenarios. However it remains an extremely useful option and is one of the more popular Design Patterns programmers are intimately familiar with, especially in web application development.
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Inheritance forces you to create a new class to extend functionality
Whereas with a decorator you can extend the functionality without creating a new class
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of Jay Roy
Jay Roy
Flag of United States of America image

ASKER

>>Inheritance requires you to create a new subclass for every different extension you require, so you could end up with a large number of subclasses.
Decorator pattern on the other hand allows you to do it with a single class.

can you give an example ?

thanks guys
Avatar of for_yan
for_yan
Flag of United States of America image



This is a very lively text talking about complexity of inheritance with examples
and of advantages of composition in many cases
http://tiedyedfreaks.org/eric/CompositionVsInheritance.html
Avatar of Ajay-Singh
Ajay-Singh

Very short answer

inheritance has is-a relationship while decorator has has-a relationship
Avatar of Jay Roy
Jay Roy
Flag of United States of America image

ASKER

ajay, intresting, i thought has-a relationship was the strategy pattern :)

SOLUTION
Avatar of Ajay-Singh
Ajay-Singh

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of Jay Roy
Jay Roy
Flag of United States of America image

ASKER

I have a base class and 3 concrete classes. The 3 concrete classes extend the base class.
public class BaseBusinessService {
      protected String getTemplateName(String id){
            String templateName = null;
             //application logic
                  }
            return templateName;            
      }
}

I have 3 concrete classes
public class ManagerBusinessService extends BaseBusinessService{
public boolean process(String Id){            
            boolean managerprocessStatus = true;                   
            String template = getTemplateName(Id);
            //work with template
            return managerprocessStatus ;
      }
}

public class CustomerBusinessService extends BaseBusinessService{
public boolean process(String Id){            
            boolean customerprocessStatus = true;            
            String template = getTemplateName(Id);
            //work with template
            return customerprocessStatus ;
      }
}

public class DirectorBusinessService extends BaseBusinessService{
public boolean process(String Id){            
            boolean directorprocessStatus = true;            
            String template = getTemplateName(Id);
            //work with template
            return directorprocessStatus ;
      }
}

So clearly i am using is- relation ship above. How can i convert the above code to has-a relationship Decorator pattern?
thanks
Avatar of Jay Roy
Jay Roy
Flag of United States of America image

ASKER

can anyone help here in putting the thoery into practice?
Java
Java

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

102K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo