【从零开始学习--设计模式--装饰者模式】

返回首页

前言

感谢各位同学的关注与支持,我会一直更新此专题,竭尽所能整理出更为详细的内容分享给大家,但碍于时间及精力有限,代码分享较少,后续会把所有代码示例整理到github,敬请期待。

此章节介绍装饰者模式。


1、代理模式

装饰器模式,允许向一个现有的对象添加新的功能,同时又不改变其结构。

这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

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

1.1、UML图

在这里插入图片描述
在这里插入图片描述

1.2、示例代码

// 版本一(搭配嘻哈服和白领装):增加其他装扮需要更改person类,违反了封闭开发原则
//V1.Person person = new V1.Person("shanyang");
//Console.WriteLine("第一种装扮:");
//person.WearTShirts();
//person.WearBigTrouser();
//person.WearSneakers();
//person.Show();
//Console.WriteLine("第二种装扮:");
//person.WearSuit();
//person.WearTie();
//person.WearShoes();
//person.Show();
//Console.ReadKey();

// 版本二(增加超人的装扮):现在是单独输出show,应该是在内部组装完毕后显示。
// 添加超人装扮需要的子类就可以了
//V2.Person person = new V2.Person("shanyang");
//Console.WriteLine("第一种装扮:");
//V2.TShirts shirts = new V2.TShirts();
//V2.BigTrouser bigTrouser = new V2.BigTrouser();
//V2.Sneakers sneakers = new V2.Sneakers();
//shirts.Show();
//bigTrouser.Show();
//sneakers.Show();
//person.Show();
//Console.WriteLine("第二种装扮:");
//V2.Suit suit = new V2.Suit();
//V2.Tie tie = new V2.Tie();
//V2.Shoes shoes = new V2.Shoes();
//suit.Show();
//tie.Show();
//shoes.Show();
//person.Show();
//Console.ReadKey();

// 版本三:装饰模式,是用SetCompenent来对对象进行包装。
V3_Decorator.Person person = new V3_Decorator.Person("shanyang");
Console.WriteLine("第一种装扮:");
V3_Decorator.TShirts shirts = new V3_Decorator.TShirts();
V3_Decorator.BigTrouser bigTrouser = new V3_Decorator.BigTrouser();
V3_Decorator.Sneakers sneakers = new V3_Decorator.Sneakers();
shirts.SetComponet(person);
bigTrouser.SetComponet(shirts);
sneakers.SetComponet(bigTrouser);
sneakers.Show();
Console.WriteLine("第二种装扮:");
V3_Decorator.Suit suit = new V3_Decorator.Suit();
V3_Decorator.Tie tie = new V3_Decorator.Tie();
V3_Decorator.Shoes shoes = new V3_Decorator.Shoes();
suit.SetComponet(person);
tie.SetComponet(suit);
shoes.SetComponet(tie);
shoes.Show();
Console.ReadKey();
  • 18
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丿Nohedid灬山羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值