How would you implement the Decorator pattern in C# to add behavior to an object without modifying its original class?
Short answer
Create a decorator class that implements the SAME interface as the object it wraps, holds a reference to the wrapped instance, and adds behavior before/after delegating the actual work to it — decorators can be chained/stacked to layer multiple behaviors independently.
Advertisement
AModel answer
Create a decorator class that implements the SAME interface as the object it wraps, holds a reference to the wrapped instance, and adds behavior before/after delegating the actual work to it — decorators can be chained/stacked to layer multiple behaviors independently.
public interface INotifier { void Send(string message); }
public class EmailNotifier : INotifier {
public void Send(string message) => Console.WriteLine($"Email: {message}");
}
public class LoggingNotifierDecorator : INotifier {
private readonly INotifier _inner;
public LoggingNotifierDecorator(INotifier inner) { _inner = inner; }
public void Send(string message) {
Console.WriteLine($"Logging: about to send '{message}'");
_inner.Send(message);
}
}Real-world example
Wrapping a core notification service with logging, retry logic, or caching behavior without modifying its original implementation.
Likely follow-ups
- How does the Decorator pattern differ from simply using inheritance to add the extra behavior?
Related topics