I have my Beverage class, which has some getters/setters to work with the size of the beverage. This program has to do with the decorator pattern, so I want to combine the behavior of some methods equally named.
My intent is to have a method with body that allows me to get the size of the beverage, but then, I want to be able to override that behavior on child classes.
In sum, I want a method that:
- if not overriden, just behaves as the method in the parent class
- if overriden, behaves like it is coded
What I did was to create a method called getSizeOfBeverage that behaves like my "old" getSize did, and made the getSize "new" method abstract so I can override it, but I want a solution that does not imply a new method name.
Here is my code:
using System;
namespace Decorator
{
class Program
{
static void Main(string[] args)
{
Beverage beverage = new Espresso("small");
beverage = new Whip(beverage);
Console.WriteLine(beverage.getDescription() + " $" + beverage.cost());
}
}
abstract class Beverage
{
private string description;
private string size;
public Beverage()
{
setDescription("Unknown beverage");
}
public double getCost()
{
return cost();
}
public abstract double cost();
public abstract string getDescription();
public void setDescription(string desc)
{
description = desc;
}
public string getSizeOfBeverage()
{
return size;
}
public abstract string getSize();
public void setSize(string sz)
{
size = sz;
}
}
class Espresso : Beverage
{
public Espresso(string sz)
{
setSize(sz);
setDescription("Espresso");
}
public override double cost()
{
return 1.9;
}
public override string getDescription()
{
return getDescription();
}
public override string getSize()
{
return getSizeOfBeverage();
}
}
abstract class CondimentDecorator : Beverage
{
public abstract override string getSize();
}
class Whip : CondimentDecorator
{
private Beverage beverage;
public Whip(Beverage bv)
{
beverage = bv;
}
public override double cost()
{
if (getSize() == "small")
{
return 0.1 + beverage.cost();
}
else if (getSize() == "medium")
{
return 0.15 + beverage.cost();
}
else
{
return 0.2 + beverage.cost();
}
}
public override string getDescription()
{
return beverage.getDescription() + ", whip";
}
public override string getSize()
{
return beverage.getSizeOfBeverage();
}
}
}