mardi 4 août 2020

Need to derive the decorator from component in decorator design pattern

I was going through design patterns tutorials and came across decorator patterns. I got a idea of how and when the decorator pattern is used however, I am bit confused on why the decorator needs to be derived from the component.

The example I saw was something as below :

//Component classes
public abstract class Car
{
   public abstract int GetPrice();
   //Other properties and methods
}

public class ActualCar
{
   public int GetPrice(){return 1000;}
}

//Decorators classes
public class CarDecorator : Car //No idea why this is necessary
{
   protected Car car;
   public CarDecorator(Car car)
   {
      this.car = car;
   }

   public override int GetPrice() => this.car.GetPrice();
}

public class LeatherSeats : CarDecorator
{
   public LeatherSeats(Car car) : base(car){}
   public override int GetPrice() => this.car.GetPrice() + 200;
}

public class AlloyWheels : CarDecorator
{
   public AlloyWheels(Car car) : base(car) {}
   public override int GetPrice() => this.car.GetPrice() + 150;
}

Now when using the component along with its decorators we use it as :

Car newCar = new ActualCar();
int price = new AlloyWheels(new LeatherSeats(newCar)).GetPrice();

Now I thought it was weird that the CarDecorator was inherited from Car as no matter how you look at it doesn't follow the is-a type of relationship. So I looked at few more examples and realized that it is how the decorator pattern is designed as.

I don't want to question the reason why the decorator pattern was designed this way, but just want to know what will be the cons of not having decorator pattern be derived from component it wraps.

Aucun commentaire:

Enregistrer un commentaire