Definition
Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Components
- ComponentBase: base class for all concrete components and decorators.
- ConcreteComponent: inherits from ComponentBase. Concrete component classes that may be wrapped by the decorators.
- DecoratorBase: base class for decorators. It has a constructor that accepts a ComponentsBase as its parameters.
- ConcreteDecorator: It may include some additional methods which extend the functionality of components.
Sample code
static class Program
{
static void Main()
{
var component = new ConcreteComponent();
var decorator = new ConcreteDecorator(component);
decorator.Operation();
}
}
public abstract class ComponentBase
{
public abstract void Operation();
}
class ConcreteComponent : ComponentBase
{
public override void Operation()
{
Console.WriteLine("ConcreteComponent.Operation()");
}
}
public abstract class DecoratorBase : ComponentBase
{
private readonly ComponentBase _component;
protected DecoratorBase(ComponentBase component)
{
_component = component;
}
public override void Operation()
{
_component.Operation();
}
}
public class ConcreteDecorator : DecoratorBase
{
public ConcreteDecorator(ComponentBase component) : base(component) { }
public override void Operation()
{
base.Operation();
Console.WriteLine("[ADDITIONAL CODE BLOCK]");
}
}
Advantages
- It helps to achieve extending the components' functionality by avoiding changing components' original logic.
- It provides a flexible alternative to subclassing for extending functionality, which could change components' behavior at runtime.
Reference
Design Patterns 2 of 3 - Structural Design Patterns - CodeProject
Head First Design Patterns - O'Reilly Media
网友评论