Drink Class 相關
namespace Beverage
{
public abstract class Drink
{
protected string DrinkName = string.Empty;
protected decimal DrinkPrice = 0.0m;
public virtual string GetDrinkName()
{
return DrinkName;
}
public abstract string GetDescript();
public abstract decimal GetPrice();
}
public class GreeTea : Drink
{
public GreeTea()
{
this.DrinkName = "綠茶";
this.DrinkPrice = 15m;
}
public override string GetDrinkName()
{
return DrinkName;
}
public override string GetDescript()
{
return $"{DrinkName} ( {DrinkPrice} )";
}
public override decimal GetPrice()
{
return DrinkPrice;
}
}
}
Decorator Class 相關namespace Beverage
{
public abstract class Decorator : Drink
{
protected Drink drink;
protected string DecoratorName = string.Empty;
protected decimal DecoratorPrice = 0.0m;
public Decorator(Drink drink)
{
this.drink = drink;
}
public override string GetDrinkName()
{
return drink.GetDrinkName();
}
public override string GetDescript()
{
return drink.GetDescript() + $", {DecoratorName} ( {DecoratorPrice} )";
}
public override decimal GetPrice()
{
return drink.GetPrice() + DecoratorPrice;
}
}
public class Bubble : Decorator
{
public Bubble(Drink drink) : base(drink)
{
this.DecoratorName = "珍珠";
this.DecoratorPrice = 10m;
}
}
public class Milk : Decorator
{
public Milk(Drink drink) : base(drink)
{
this.DecoratorName = "牛奶";
this.DecoratorPrice = 21m;
}
}
public class Yakult : Decorator
{
public Yakult(Drink drink) : base(drink)
{
this.DecoratorName = "養樂多";
this.DecoratorPrice = 10m;
}
public override string GetDrinkName()
{
return $"{DecoratorName} - {drink.GetDrinkName()}";
}
}
}
執行namespace Beverage
{
class Program
{
static void Main(string[] args)
{
Drink d1 = new GreeTea();
d1 = new Bubble(d1);
d1 = new Yakult(d1);
ShowData(d1);
}
private static void ShowData(Drink d)
{
Console.WriteLine($"品名:{d.GetDrinkName()}");
Console.WriteLine($"價格:{d.GetPrice()}");
Console.WriteLine($"說明:{d.GetDescript()}");
}
}
}
結果