Design-Patterns icon indicating copy to clipboard operation
Design-Patterns copied to clipboard

Discuss about Decorator pattern in Little Kai example

Open Cotel opened this issue 7 years ago • 6 comments

What do you think? What would you change?

Cotel avatar Mar 04 '17 17:03 Cotel

Updated master to use kotlin's keyword by in SauceDecorator. Do you like it?

Cotel avatar Mar 07 '17 20:03 Cotel

Can Decorators be implemented through kotlin's extension functions too? The Decorator would define a new function for the decorated class.

In our case, IngredientDecorator would define calculateCost() for Noodles

Cotel avatar Mar 07 '17 20:03 Cotel

You could do an example

tonilopezmr avatar Mar 07 '17 23:03 tonilopezmr

I've been trying and I don't think it is possible.

1st reason is extension functions scope is really strange. If I declare an extension function for Noodles inside IngredientDecorator it will never be reached from nowhere.

2nd reason. In my example i have removed calculateCost from Noodles and I declare it as an extension function in IngredientDecorator:

abstract class IngredientDecorator(protected val noodles: Noodles) : Noodles {
  override abstract protected val cost : Double

  fun Noodles.calculateCost() : Double = noodles.cost + cost // Both of this costs are referencing Noodles.costs
}

The problem is, when you declare an extension function, this inside that scope is the class which we are extending (in this case is Noodles). So, I cannot access to IngredientDecorator's cost.

3rd problem is that if we do calculateCost this way it won't increase if we add more ingredients because Noodles cost will be a constant value, it will not calculate recursively if it is another decorator.

Cotel avatar Mar 08 '17 07:03 Cotel

Ok, I've been reading Decorator's entry in Wikipedia and we are doing this pattern badly.

As @srgtrujillo said, the Decorator pattern Adds behaviour to an object and gives the possibility to remove it too. It adds responsabilities to an object dynamically and in a transparent way. It can be used when extension via inheritance is not possible or when there is no good reason to use it.

So, what do you want to do? It is better to make another example? We keep this one even with that new implementation? It was a good idea but we are losing the point with the new changes. Keeping calculateCost() in decorated noodles has no sense in my opinion. You don't need to know how much the base noodles cost after you added things to them, you are interested in the final price.

We can think of another example for decorators within Little Kai example.

Cotel avatar Mar 15 '17 19:03 Cotel

I said that in class that isn't a good example

tonilopezmr avatar Mar 17 '17 11:03 tonilopezmr