head first 设计模式学习随笔(3)----装饰者模式

本文深入解析装饰者模式的概念及其在实际场景中的应用,通过以咖啡饮料为例,详细阐述如何通过装饰者模式实现功能的动态扩展,同时遵循设计模式原则,展示其在软件设计中的灵活性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

装饰者模式,所谓装饰者模式,就是能够自由动态扩展功能,装饰者和被装饰折拥有同一个超类,比如System.IO系统,

我个人认为的装饰者模式就是 (((被装饰者)装饰者+)+装饰者)+装饰者.....无穷无尽的扩展.....

该模式也符合设计模式原则:

开-闭原则对扩展开放,对修改关闭.

优先使用组合而非继承,不过这里继承的目的不是为了获得行为而是为了匹配类型

以下以咖啡饮料为例解释装饰者模式:

 

 1    /**//// <summary>
 2    /// 被装饰者超类
 3    /// </summary>

 4    public abstract class super
 5    {
 6        public abstract void write();
 7    }

 8    /**//// <summary>
 9    /// 装饰者继承超类
10    /// </summary>

11    public abstract class Component:super
12    {
13        public abstract void getTotal();
14    }

15
16    /**//// <summary>
17    /// 被装饰者
18    /// </summary>

19    public class decker:super
20    {
21        string name;
22        int price;
23
24        public decker(string name, int price)
25        {
26            this.name = name;
27            this.price = price;
28        }

29        public override void write()
30        {
31            Console.WriteLine(string.Format(@"我是被装饰者:{0},我的价格是{1}", name, Price));
32        }

33    }

34    /**//// <summary>
35    /// 装饰者
36    /// </summary>

37    public class decoratee : Component
38    {
39        string name;
40        int price;
41        super s;
42
43        public decoratee(string name, int price,super s)
44        {
45            this.name = name;
46            this.price = price;
47            this.s = s;
48        }

49        public override void getTotal()
50        {
51            write();
52        }

53        public override void write()
54        {
55            s.write();
56            //自定义方法
57            Console.WriteLine(string.Format(@"我是装饰者:{0},我的价格是{1}", name, price));
58        }

59    }

60
61    class Program
62    {
63        static void Main(string[] args)
64        {
65            //定义被装饰者
66            super d_1 = new decker("卡布奇诺"15);
67            //定义被装饰者
68            Component dec_1 = new decoratee(""3, d_1);
69            //循环包装
70            dec_1 = new decoratee("吸管"2, dec_1);
71            dec_1 = new decoratee("大杯子"2, dec_1);
72            dec_1 = new decoratee("精美包装盒"4, dec_1);
73            dec_1 = new decoratee("牛奶"1, dec_1);
74
75            //统计
76            dec_1.getTotal();
77            Console.ReadKey();
78        }

79    }
 


运行结果:

转载于:https://www.cnblogs.com/jimmypony/archive/2008/09/18/1293030.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值