设计模式之一——Decorator(修饰)
2009-02-15 17:43
274 查看
定义:
动态的给一个对象添加额外职责,Decorator提供了为子类扩展的功能。
UML:
用途:
Decorator非常适合图形程序,也同样适合音频和视频。
在c#中I/O API 都是利用Decorator模式实现。
System.IO.Stream
System.IO.BufferedStream
System.IO.FileStream
System.IO.MemoryStream
System.Net.Sockets.NetworkStream
System.Security.Cryptography.CryptoStream
在.NET3.0中已有实际的装饰器类了。System.Windows.Controls命名空间中提供了一些基类,也用于给其他的图形
元素添加特殊效果,如Border和Viewbox
代码:
对于Decorator模式有一点很重要:它基于新对象被创建出来时具有自己的操作,有些操作可以被继承,但只能继承一层。
动态的给一个对象添加额外职责,Decorator提供了为子类扩展的功能。
UML:
用途:
Decorator非常适合图形程序,也同样适合音频和视频。
在c#中I/O API 都是利用Decorator模式实现。
System.IO.Stream
System.IO.BufferedStream
System.IO.FileStream
System.IO.MemoryStream
System.Net.Sockets.NetworkStream
System.Security.Cryptography.CryptoStream
在.NET3.0中已有实际的装饰器类了。System.Windows.Controls命名空间中提供了一些基类,也用于给其他的图形
元素添加特殊效果,如Border和Viewbox
代码:
using System; class DecoratorPattern { // Shows two decorators and the output of various // combinations of the decorators on the basic component interface IComponent { string Operation(); } class Component : IComponent { public string Operation() { return "Component"; } } class DecoratorA : IComponent { IComponent component; public DecoratorA(IComponent c) { component = c; } public string Operation() { string s = component.Operation(); s += " DecoratorA"; return s; } } class DecoratorB : IComponent { IComponent component; public string addedState = "DecoratorB_addedState"; public DecoratorB(IComponent c) { component = c; } public string Operation() { string s = component.Operation(); s += " DecoratorB"; return s; } public string AddedBehavior() { return "DecoratorB_AddedBehavior"; } } class Client { static void Display(string s, IComponent c) { Console.WriteLine(s + c.Operation()); } static void Main() { Console.WriteLine("Decorator Pattern/n"); IComponent component = new Component(); Display("1. Basic component: ", component); Display("2. A-decorated : ", new DecoratorA(component)); Display("3. B-decorated : ", new DecoratorB(component)); Display("4. B-A-decorated : ", new DecoratorB( new DecoratorA(component))); // Explicit DecoratorB DecoratorB b = new DecoratorB(new Component()); Display("5. A-B-decorated : ", new DecoratorA(b)); // Invoking its added state and added behavior Console.WriteLine("/t/t/t" + b.addedState + b.AddedBehavior()); } } }
对于Decorator模式有一点很重要:它基于新对象被创建出来时具有自己的操作,有些操作可以被继承,但只能继承一层。
相关文章推荐
- 设计模式(12)-Decorator 修饰模式
- nf设计模式 - 修饰模式 (Decorator pattern) 的 Java 实现
- 设计模式学习笔记——修饰模式(Decorator Pattern)
- python: 设计模式(design pattern)之修饰器模式(decorator)
- 常见设计模式的解析和实现(C++)之九—Decorator模式
- 设计模式-装饰模式-decorator-python
- 黑马程序员————JAVA 设计模式— 装饰模式(Decorator)详解。
- 设计模式之八------Decorator(装饰)
- Python的结构型设计模型之修饰器模式
- 设计模式实践(四)装饰模式(decorator)
- 设计模式——Decorator模式
- 23设计模式之装饰模式(Decorator)
- 乐在其中设计模式(C#) - 装饰模式(Decorator Pattern)
- 装饰设计模式(decorator design pattern)
- [转] 设计模式---装饰模式(Decorator)
- 设计模式2--装饰模式(the decorator design pattern)
- [设计模式]装饰器模式(Decorator)
- java设计模式进阶_decorator
- 设计模式学习--装饰者模式(Decorator Pattern)