Skip to content

Decorator

Context: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

public interface IComponent
{
void Operation();
}
public class ConcreteComponent : IComponent
{
public void Operation() => Console.WriteLine("Component operation");
}
public abstract class Decorator : IComponent
{
protected IComponent _component;
public Decorator(IComponent component) => _component = component;
public virtual void Operation() => _component.Operation();
}
public class ConcreteDecoratorA : Decorator
{
public ConcreteDecoratorA(IComponent c) : base(c) { }
public override void Operation()
{
base.Operation();
Console.WriteLine("Added behavior A");
}
}

Streams in .NET: FileStream can be decorated with BufferedStream, CryptoStream, GZipStream to add buffering, encryption, or compression without changing the original stream.

Example: ASP.NET Core middleware is a decorator pipeline: each middleware decorates the next, adding logging, authentication, caching, etc. System.IO.Stream decorators include GZipStream, CryptoStream.