Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorator pattern example

I was going through the Decorator design pattern and saw that every second example uses an Abstract decorator class and also implement the interface of the class for which decorator is to be created. My question is,

  1. Is it necessary to have an abstract decorator class and then define the concrete decorators ?

  2. I have created a sample which i think can resemble the functionality which is being achieved by the above mentioned Abstract class approach.

     public interface ICarModel
     {
       Int32 Price { get; }
       Int32 Tax { get; }
     }
    
     public class BaseModel : ICarModel
     {
       public Int32 Price
       {
         get { return 50000; }
       }
    
       public Int32 Tax
       {
         get { return 5000; }
       }
    
       public String GetBaseCarDetails()
       {
         return "Base car model Price is : " + this.Price
           + " and Tax is : " + this.Tax;
       }
     }
    
     public class LuxuryModel
     {
       ICarModel _iCarModel;
    
       public LuxuryModel(ICarModel iCarModel)
       {
         _iCarModel = iCarModel;
       }
    
       public Int32 Price
       {
         get { return _iCarModel.Price + 10000; }
       }
    
       public Int32 Tax
       {
         get { return _iCarModel.Tax + 3000; }
       }
    
       public String GetLuxuryCarDetails()
       {
         return "Luxury car model Price is : " + this.Price
           + " and Tax is : " + this.Tax;
       }
     }
    

    Can we say that this is an example of the decorator pattern ?

like image 393
Tech Jay Avatar asked Nov 21 '13 15:11

Tech Jay


2 Answers

Update

Do we really need to make the decorator as abstract class ?

I guess you could avoid abstract but then you would have to write the same code for all your classes. The purpose of abstract is to avoid redundant code and insure that your classes comply to the same logic. Also it is easier to maintain and scale.

Decorator Pattern

like image 92
giannis christofakis Avatar answered Nov 03 '22 08:11

giannis christofakis


The intent of the decorator pattern is simply to extend the behavior of an existing type in such a way that consumers of that type don't need to know the implementation details of how it has changed.

There's no requirement for any of the types to be abstract. You can do this with interfaces or with virtual methods on concrete classes.

like image 25
Martin Cron Avatar answered Nov 03 '22 09:11

Martin Cron