装饰模式 Decorator
结构: 意图:
动态的给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
适用性:
l 在不影响其它对象的情况下,以动态、透明的方式给单个对象添加职责。
l 处理那些可以撤销的职责。
l 当不能以生成子类的方法进行扩充时。
n 一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。
n 另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。
示例:
- // Decorator
- // Intent: "Attach additional responsibilites to an object dynamically.
- // Decorators provide a flexible alternative to subclassing for
- // extending functionality".
- //动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式较之于子类提供了一种更加灵活的方式。
- // For further information, read "Design Patterns", p175, Gamma et al.,
- // Addison-Wesley, ISBN:0-201-63361-2
- /* Notes:
- * Dynamically wrap functionality with additonal functionality, so that
- * the client does not know the difference.
- */
- namespace Decorator_DesignPattern
- {
- using System;
- abstract class Component
- {
- public abstract void Draw();
- }
- class ConcreteComponent : Component
- {
- private string strName;
- public ConcreteComponent(string s)
- {
- strName = s;
- }
- public override void Draw()
- {
- Console.WriteLine("ConcreteComponent - {0}", strName);
- }
- }
- abstract class Decorator : Component
- {
- protected Component ActualComponent;
- public void SetComponent(Component c)
- {
- ActualComponent = c;
- }
- public override void Draw()
- {
- if (ActualComponent != null)
- ActualComponent.Draw();
- }
- }
- class ConcreteDecorator : Decorator
- {
- private string strDecoratorName;
- public ConcreteDecorator(string str)
- {
- // how decoration occurs is localized inside this decorator
- // For this demo, we simply print a decorator name
- strDecoratorName = str;
- }
- public override void Draw()
- {
- CustomDecoration();
- base.Draw();
- }
- void CustomDecoration()
- {
- Console.WriteLine("In ConcreteDecorator: decoration goes here");
- Console.WriteLine("{0}", strDecoratorName);
- }
- }
- ///
- /// Summary description for Client.
- ///
- public class Client
- {
- Component Setup()
- {
- ConcreteComponent c = new ConcreteComponent("This is the real component");
- ConcreteDecorator d = new ConcreteDecorator("This is a decorator for the component");
- d.SetComponent(c);
- return d;
- }
- public static int Main(string[] args)
- {
- Client client = new Client();
- Component c = client.Setup();
- // The code below will work equally well with the real component,
- // or a decorator for the component
- c.Draw();
- Console.Read();
- return 0;
- }
- }
- }
阅读(863) | 评论(0) | 转发(0) |