Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying Decorator Design Pattern, what's wrong with this code?

I have this code that explains the decorator pattern:

 public abstract class IBeverage {
    protected string description = "Unknown beverage";

    public virtual string getDescription() {
        return description;
    }
}

public abstract class CondimentDecorator : IBeverage {
    public abstract string getDescription();
}

public class Espresso : IBeverage {
    public Espresso() {
        description = "Espresso";
    }
}

public class Mocha : CondimentDecorator {
    IBeverage beverage;

    public Mocha(IBeverage beverage) {
        this.beverage = beverage;
    }

    public override string getDescription() {
        return beverage.getDescription() + ", Mocha";
    }
}

I should use it like:

static void Main(string[] args) {
    IBeverage b = new Espresso();
    Console.WriteLine(b.getDescription());
    b = new Mocha(b);
    Console.WriteLine(b.getDescription());

    Console.ReadKey();
}

When I create the beverage (Beverage b = new Espresso();) _description is updated to "Espresso", when I decorate b with Mocha (b = new Mocha(b)), then _description takes the original value "Unknown Beverage". It should be "Espresso, Mocha". What's wrong?

This code was originally written in Java (the book was written with Java), but I translated it into C#. I guess Java works a little different from C#.

like image 789
Rafael Avatar asked Dec 02 '25 10:12

Rafael


1 Answers

Because GetDescription() is not virtual.

public virtual string GetDescription() { ... }

virtual is the companion keyword to override, it's what allows subclasses to override methods. This is a key difference in C# from Java. In Java all methods are implicitly virtual.

like image 93
Matt Greer Avatar answered Dec 05 '25 11:12

Matt Greer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!