samedi 11 août 2018

Why we need abstract decorator class in Decorator Pattern?

In Decorator Pattern, if I

  1. remove the abstract decorator class which decorators was inherit and
  2. has decorators directly inherit the interface of decoratee.

The output is the same.

My question is why bother adding additional abstractor class to make a decorator ?

For example:
The Scala source code of standard decorator pattern is here: https://gist.github.com/kencoba/1875983
My version is : (by remove the abstract decorator class (CoffeeDecorator here) and has decorators directly inherit the decoratee (Coffee here))

trait Coffee {
  def cost: Double
  def ingredients: String
}

//abstract class CoffeeDecorator(decoratedCoffee: Coffee) extends Coffee {
//  val sep = ", "
//
//  override def cost = decoratedCoffee.cost
//  override def ingredients = decoratedCoffee.ingredients
//}

class Milk(decoratedCoffee: Coffee) extends Coffee {
  override def cost = decoratedCoffee.cost + 0.5
  override def ingredients = decoratedCoffee.ingredients + "," + "Milk"
}

class Whip(decoratedCoffee: Coffee) extends Coffee {
  override def cost = decoratedCoffee.cost + 0.7
  override def ingredients = decoratedCoffee.ingredients + "," + "Whip"
}


object DecoratorSample {... // same as the comparing source code.

Aucun commentaire:

Enregistrer un commentaire