C#设计模式——(结构型-装饰器设计模式)

2022-10-10 17:51:02 浏览数 (1)

一、应用场景

奶茶店里售卖不同饮料,搭配不同配料。

如果想要一杯奶茶,加两份布丁,加一份珍珠。

二、装饰器模式定义

动态的给一个对象添加一些额外的职责,就增加功能来说比添加子类更加灵活。

有效的把类的核心职责和装饰功能分开解耦了。

示例代码:

代码语言:javascript复制
       public abstract class YinLiao
        {
            public abstract double Cost();
        }
        public class MilkTea : YinLiao
        {
            public override double Cost()
            {
                Console.WriteLine("奶茶10一杯");
                return 10;
            }
        }
        public class FruitTea : YinLiao
        {
            public override double Cost()
            {
                Console.WriteLine("果茶20一杯");
                return 10;
            }
        }
        public class SudaTea : YinLiao
        {
            public override double Cost()
            {
                Console.WriteLine("苏打饮料20一杯");
                return 10;
            }
        }
        //Decorater类
        public abstract class Decorater:YinLiao
        {
            //添加父类的引用
            private YinLiao Yinglaio;
            //通过set方法,给他赋值
            public void SetComponent(YinLiao yinglaio)
            {
                this.Yinglaio = yinglaio;
            }
            public override double Cost()
            {
               return this.Yinglaio.Cost();
            }
        }
        public class Buding:Decorater
        {
            private static double money = 5;
            public override double Cost()
            {
                Console.WriteLine("布丁5块");
                return base.Cost() money;
            }
        }
        public class XianCao : Decorater
        {
            private static double money = 6;
            public override double Cost()
            {
                Console.WriteLine("仙草6块");
                return base.Cost()   money;
            }
        }
        public class Zhenzhu : Decorater
        {
            private static double money = 7;
            public override double Cost()
            {
                Console.WriteLine("珍珠5块");
                return base.Cost()   money;
            }
        }
代码语言:javascript复制
            MilkTea milkTea = new MilkTea();
            Buding buding1 = new Buding();
            Buding buding2= new Buding();
            Zhenzhu zhenzhu = new Zhenzhu();
            buding1.SetComponent(milkTea);
            buding2.SetComponent(buding1);
            zhenzhu.SetComponent(buding2);
            Console.WriteLine(zhenzhu.Cost());

0 人点赞