SOLID & Design Patterns Interview Question #25

What is the Decorator Pattern?

SOLID Principles, Design Fundamentals, Repository, Factory, Strategy & Decorator Junior Beginner

Quick Interview Answer

The Decorator Pattern wraps an object that implements an interface and adds behavior before or after delegating to the wrapped object. Multiple decorators can be composed without modifying the original implementation.

Detailed Explanation

The Decorator Pattern wraps an object that implements an interface and adds behavior before or after delegating to the wrapped object. Multiple decorators can be composed without modifying the original implementation.

It is useful for cross-cutting or optional behavior such as caching, logging, metrics, retries, or validation when those concerns can be expressed around an existing operation.

Code Example

public class LoggingEmailSender : IEmailSender
{
    private readonly IEmailSender _inner;

    public LoggingEmailSender(IEmailSender inner)
    {
        _inner = inner;
    }

    public async Task SendAsync(string to, string subject)
    {
        Console.WriteLine("Sending email");
        await _inner.SendAsync(to, subject);
    }
}