装饰器模式

一、定义

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

二、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 2023-05-29 13:32  一只向上爬的小蜗牛  阅读(13)  评论(0编辑  收藏  举报