装饰器模式

一、定义

装饰器模式动态地给一个对象增加一些额外的职责。就增加功能而言,装饰器模式比生成子类更为灵活。

二、UML类图

三、示例

需求:假设开一个奶茶店,奶茶种类繁多,如红豆奶茶,布丁奶茶,珍珠奶茶,红豆珍珠奶茶等,并根据不同配料计算价格,并且根据每个客户的要求,每种奶茶又可以加糖或者加冰,加糖加冰不额外收费。

通过组合+继承的方式改进,可使得饮品的扩展更灵活,同时也遵守了开闭原则。其中,组合是为了实现功能,而继承是为了约束类型,这其实就是装饰者模式。

代码:

1.Drink.cs

复制代码
public abstract class Drink
    {
        public string Name { get; set; }

        public int Price { get; set; }

        public abstract string Desc { get; }

        public abstract int Cost { get; }
    }
复制代码

2.Naicha.cs

复制代码
public class Naicha : Drink
    {
        public Naicha()
        {
            Name = "奶茶";
            Price = 8;
        }
        public override string Desc => this.Name;
        public override int Cost => this.Price;
    }
复制代码

3.Peiliao.cs

复制代码
public class Peiliao:Drink
    {
        protected readonly Drink Drink;

        public Peiliao(Drink drink)
        {
            Drink = drink;
        }

        public override string Desc
        {
            get
            {
                return Drink.Desc + "+" + this.Name;
            }
        }

        public override int Cost
        {
            get
            {
                return Drink.Cost + this.Price;
            }
        }
    }
复制代码

4.Hongdou.cs

public class Hongdou : Peiliao
    {
        public Hongdou(Drink drink) : base(drink)
        {
            Name = "红豆";
            Price = 1;
        }
    }

5.Program.cs

复制代码
internal class Program
    {
        static void Main(string[] args)
        {
            Drink drink = new Naicha();
            drink = new Hongdou(drink);
            drink = new Bing(drink);
            drink = new Buding(drink);
            Console.WriteLine($"描述:{drink.Desc},价格:{drink.Cost}");

            Drink drink2 = new Kafei();
            drink2 = new Kafeibanlv(drink2);
            drink2 = new Tang(drink2);
            Console.WriteLine($"描述:{drink2.Desc},价格:{drink2.Cost}");
        }
    }
复制代码

运行结果:

 

四、总结

优缺点
1.优点
可动态的给一个对象增加额外的职责
有很好地可扩展性
2.缺点
增加了程序的复杂度,刚接触理解起来会比较困难

 

posted on   一只向上爬的小蜗牛  阅读(15)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示