您的位置:首页 > 其它

设计模式之一——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 

代码:

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模式有一点很重要:它基于新对象被创建出来时具有自己的操作,有些操作可以被继承,但只能继承一层。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息