C# Interview Question #157

What is the Decorator Pattern?

Design Patterns & Production Architecture Senior Advanced

Quick Interview Answer

The Decorator Pattern wraps an existing implementation of an interface to add behavior without modifying the original implementation.

Detailed Explanation

The Decorator Pattern wraps an existing implementation of an interface to add behavior without modifying the original implementation.

Decorators are useful for logging, caching, validation, retries, metrics, authorization, and other cross-cutting behavior.

For example, a CachedProductService can implement IProductService, delegate actual retrieval to another IProductService, and add caching around the operation.

Code Example

public class LoggingProductService : IProductService
{
    private readonly IProductService _inner;
    private readonly ILogger<LoggingProductService> _logger;

    public LoggingProductService(
        IProductService inner,
        ILogger<LoggingProductService> logger)
    {
        _inner = inner;
        _logger = logger;
    }

    public async Task<Product?> GetAsync(int id)
    {
        _logger.LogInformation(
            "Loading product {ProductId}", id);

        return await _inner.GetAsync(id);
    }
}