结构型模式之装饰模式(Decorator)
来源:互联网 发布:苹果内购验证 java 编辑:程序博客网 时间:2024/05/29 11:44
结构型模式的特点就是从程序的结构上解决模块之间的耦合问题。其中结构型模式包括:适配器模式、装饰模式、桥接模式、组合模式、享元模式、代理模式、外观模式。这里,我们重点说一下装饰模式。
引起:
代码:
{ class Program { static void Main(string[] args) { Person xc = new Person("小菜"); Console.WriteLine("第一种装扮"); Finery dtx = new TShirts(); Finery kk = new BigTrouser(); dtx.Show(); kk.Show(); xc.Show(); Console.Read(); } } class Person { private string name; public Person(string name) { this.name = name; } public void Show() { Console.WriteLine("装扮的{0}", name); } } abstract class Finery { public abstract void Show(); } class TShirts : Finery { public override void Show() { Console.Write("体恤"); } } class BigTrouser : Finery { public override void Show() { Console.Write("垮裤"); } }}
结果:
问题:
虽然做到了服饰类和人类的分离,但是还存在没有把所需的功能按照正确的顺序串联起来而进行控制。
定义:
装饰模式,动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
结构图:
代码:
class Program { static void Main(string[] args) { Person xc = new Person("小菜"); Console.WriteLine("\n第一种装扮:"); TShirts dtx = new TShirts(); BigTrouser kk = new BigTrouser(); dtx.Decorate(xc); kk.Decorate(dtx); kk.Show(); Console.Read(); } } class Person { public Person() { } private string name; public Person(string name) { this.name = name; } public virtual void Show() { Console.WriteLine("装扮的{0}", name); } } class Finery : Person { protected Person component(); public void Decorate(Person component) { this.component = component; } public override void Show() { if (component != null) { component.Show(); } } } class TShirts : Finery { public override void Show() { Console.Write("大体恤"); base.Show(); } } class BigTrouser : Finery { public override void Show() { Console.Write("垮裤"); base.Show(); } }
优点:
把类中的装饰功能从类中 搬移去除了,这样可以简化原有的类,有效的把类的核心职责和装饰功能区分开了,去除了重复的装饰逻辑,让代码更具有拓展性。
0 0
- 结构型模式之装饰(Decorator)
- 结构型模式之装饰者模式(Decorator)
- 结构型模式之装饰模式(Decorator)
- 结构型模式之装饰模式(Decorator)
- 结构型模式-----装饰模式(decorator)
- Decorator模式(装饰模式 结构型)
- 结构型模式之装饰DECORATOR
- Decorator 装饰(结构型模式)
- 结构型模式:Decorator(装饰)
- 装饰器模式Decorator(结构型)
- Decorator装饰设计模式(结构型)
- 装饰模式Decorator(结构型)
- Decorator装饰(结构型模式)
- 【结构型模式】decorator(装饰)
- 结构型模式-装饰(decorator)
- 九、结构模式之装饰(Decorator)模式
- 结构型模式之装饰模式(Decorator Pattern)C++实现
- 设计模式(结构型)之装饰者模式(Decorator Pattern)
- Linux Kernel Panic报错解决思路
- CSS中display对布局的影响以及元素display的默认值
- PlatformBuilder - Windows CE Platform Builder 5.0 WinCE
- sina 微博 Oauth1.0接口
- sql server 2008 游标
- 结构型模式之装饰模式(Decorator)
- 压缩和解压缩& 关机重启
- 黑马程序员-iOS基础-Objective-C基础(一)
- ios 分享功能 集成友盟分享
- java paintComponent的一些解读
- 用Python写八数码问题
- iOS 获取设备系统信息
- POJ1502 MPI Maelstrom(最短路dijkstra)
- 一般函数指针和类的成员函数指针