Is it possible to remove a decorator from an object?
Say I have the following code:
abstract class Item
{
decimal cost();
}
class Coffee : Item
{
decimal cost()
{ // some stuff }
}
abstract class CoffeeDecorator : Item
{
Item decoratedItem;
}
class Mocha : CoffeeDecorator
{
Item decoratedItem;
public Mocha(Coffee coffee)
{
decoratedItem = coffee;
}
}
public void Main(string[] args)
{
Item coffeeDrink = new Mocha(new Coffee());
}
Is there a way to remove the “new Mocha()” from my new “coffee” object?
EDIT: Clarification – I want to be able to remove just ONE decorator, not all of them. So if I had a Mocha decorator AND a Sugar decorator on the Coffee object, I want to know if I can remove just the “Mocha” decorator.
First, this assignment is not legal:
A
Mochais not aCoffeenor is there an implicit cast from aMochato aCoffee. To “remove” the decorator, you need to provide either a method or a cast to do so. So you could add an undecorate method toMocha:Then you could say
Alternatively, you could provide an implicit cast operator in the
Mochaclass:Then your line
would be legal.
Now, your question suggests a potential misunderstanding of the design pattern (and, in fact, your implementation suggests one too). What you’re trying to do is very smelly. The right way to go about using the decorator pattern is like so. Note that
CoffeeDecoratorderives fromCoffee!Then you can say:
Given this, what do you need to undecorate it for?