标签:源码 包装 esc on() 构建 abstract line uri 测试
装饰者模式动态地将责任附加到对象上。若要拓展功能,装饰者提供了比继承更有弹性的替代方案。
public abstract class MilkyTea(奶茶)
{
public string description;
public abstract double GetFee();
//与java不一样,java父类方法不需要加关键词Virtual就可以在子类中重写
public virtual string GetDescription()
{
return description;
}
}
public class MilkGreenTea : MilkyTea
{
public MilkGreenTea()
{
description = "Milk Green Tea";
}
public override double GetFee()
{
return 10;
}
}
public abstract class CondimentDecorator : MilkyTea
{
public MilkyTea milkyTea;
}
public class Oats : CondimentDecorator
{
public Oats(MilkyTea milkyTea)
{
this.milkyTea = milkyTea;
}
public override double GetFee()
{
return 1 + milkyTea.GetFee();
}
public override string GetDescription()
{
return milkyTea.GetDescription() + ",Oats";
}
}
public class Pudding : CondimentDecorator
{
public Pudding(MilkyTea milkyTea)
{
this.milkyTea = milkyTea;
}
public override double GetFee()
{
return 3 + milkyTea.GetFee();
}
public override string GetDescription()
{
return milkyTea.GetDescription() + ",Pudding";
}
}
static void Main(string[] args)
{
MilkyTea tea = new MilkGreenTea();
Console.WriteLine($"{tea.GetDescription()}:¥{tea.GetFee()}。");
tea = new Pudding(tea);
Console.WriteLine($"{((Pudding)tea).GetDescription()}:¥{tea.GetFee()}。");
tea = new Oats(tea);
Console.WriteLine($"{tea.GetDescription()}:¥{tea.GetFee()}。");
}
https://github.com/DonyGu/DesignPatterns
标签:源码 包装 esc on() 构建 abstract line uri 测试
原文地址:https://www.cnblogs.com/donyblog/p/11392037.html