SOLID & Design Patterns Interview Question #95

How can the Decorator Pattern be used for caching?

DDD Boundaries, Resilience, Caching & Practical ASP.NET Core Design Mid-Level Intermediate

Quick Interview Answer

A caching decorator implements the same interface as the underlying service or repository. It checks the cache first and delegates to the wrapped implementation only when necessary.

Detailed Explanation

A caching decorator implements the same interface as the underlying service or repository. It checks the cache first and delegates to the wrapped implementation only when necessary.

This keeps caching logic separate from the core implementation and allows the decorator to be composed or removed without changing callers.

Code Example

public class CachedProductService : IProductService
{
    private readonly IProductService _inner;
    private readonly ICache _cache;

    public async Task<Product?> GetAsync(int id)
    {
        var cached = await _cache.GetAsync<Product>(id.ToString());
        return cached ?? await _inner.GetAsync(id);
    }
}