设计模式之装饰者模式,奶茶店场景
// See https://aka.ms/new-console-template for more information using System.Drawing; /*
装饰者模式,不改变实现类的情况下,动态给实现类增加新功能,这里使用聚合关系实现
奶茶店 实现点奶茶加不同的料,计算价格的场景,使用装饰者模式实现 优点,新增一种小料时只需要实现IDecorator接口即可扩展,符合开闭原则 */ var beverage = new MilkTea(); //先点一杯奶茶 beverage.Add(new Pudding()); //加一份布丁 beverage.Add(new Boba()); //加一份珍珠 Console.WriteLine($"Hello, World {beverage.Cost()}"); //算出价格 /// <summary> /// 饮料基类 /// </summary> abstract class Beverage { protected readonly List<IDecorator> decorators; //聚合多种小料 public Beverage() { decorators = new List<IDecorator>(); } public void Add(IDecorator decorator) { decorators.Add(decorator); } public abstract double Cost(); } /// <summary> /// 奶茶 /// </summary> class MilkTea : Beverage { private double PRICE = 15; public override double Cost() { return PRICE + decorators.Sum(s => s.Price); } } /// <summary> /// 水果茶 /// </summary> class FruitTea : Beverage { private double PRICE = 20; public override double Cost() { return PRICE + decorators.Sum(s => s.Price); } } /// <summary> /// 小料接口(装饰者) /// </summary> interface IDecorator { double Price { get; set; } } /// <summary> /// 布丁 3元一份 /// </summary> class Pudding : IDecorator { public double Price { get; set; } = 3; } /// <summary> /// 珍珠 两元一份 /// </summary> class Boba : IDecorator { public double Price { get; set; } = 2; }
Newd
版权声明
作者:も不秃不秃
地址:https://www.cnblogs.com/Newd/p/17222901.html
© Newd 尊重知识产权,引用请注出处
广告位
(虚位以待,如有需要请私信)