Design-Patterns
Design-Patterns copied to clipboard
Discuss about Decorator pattern in Little Kai example
What do you think? What would you change?
Updated master
to use kotlin's keyword by
in SauceDecorator
. Do you like it?
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
You could do an example
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.
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.
I said that in class that isn't a good example