设计模式学习4——装饰模式
2018-10-20 00:49
113 查看
定义
装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就添加功能来说,装饰模式比生成子类更加灵活。
结构图
分析
装饰模式是利用Operation来对对象进行包装。这样每个装饰对象的实现和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当众。
如果只有一个ConcreteComponet类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。
代码实例
为张三进行装扮,上身T恤衫,下身牛仔裤,鞋子是球鞋。
[code]using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication7 { 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 Tshirt : Finery { public override void Show() { Console.Write("T恤衫 "); base.Show(); } } class Qiuxie : Finery { public override void Show() { Console.Write("球鞋 "); base.Show(); } } class Niuzaiku : Finery { public override void Show() { Console.Write("牛仔裤 "); base.Show(); } } class Program { static void Main(string[] args) { Person ps = new Person("张三"); Tshirt tshirt = new Tshirt(); Qiuxie qx = new Qiuxie(); Niuzaiku nzk = new Niuzaiku(); tshirt.Decorate(ps); qx.Decorate(tshirt); nzk.Decorate(qx); nzk.Show(); Console.ReadLine(); } } }
每个show结束后,都会运行上一层的show。此处的show即为要添加的方法。
相关文章推荐
- 8.2_java学习_装饰设计模式
- 设计模式学习-Decorator(装饰)
- 软件工程 - 设计模式学习之装饰模式Decorator
- java 设计模式学习笔记九 decorator装饰模式
- 设计模式学习笔记--装饰器模式
- 设计模式学习:装饰模式
- Java设计模式(学习整理)----装饰模式
- IO学习(十六)装饰设计模式
- “设计模式”学习之三:适配器、装饰模式
- 设计模式学习-Decorator(装饰)
- 设计模式 学习笔记 之 装饰模式 Decorator(6)
- 学习设计模式之结合简单工厂,策略,装饰的计算器
- Java设计模式学习09——装饰模式
- java 设计模式学习笔记九 decorator装饰模式
- 从FLC中学习的设计模式系列-结构型模式(2)-装饰
- java设计模式学习笔记之装饰模式
- 设计模式学习系列七:装饰模式(Decorator)
- C#设计模式学习小结之二 装饰模式
- Java设计模式学习记录-装饰模式
- 设计模式学习笔记-装饰模式