wasAsked.

Which Design Pattern and explain and write the code for this?

Agiliad Technologies Pvt Ltd · Role not specified · technical

Published

Asked in 2026 · System Design

Community answers

Posted by wasAsked editorial collection

Pick a pattern you have actually used, explain the problem it solved, show compact code, and mention trade-offs. A good choice is the Decorator pattern, because it appears naturally in .NET applications for caching, logging and retries. Decorator pattern Adds behaviour to an object dynamically by wrapping it in another object that implements the same interface, without changing the original class. It follows the Open/Closed and Single Responsibility principles. Problem in my project (example) "Our product catalog repository was slow for frequently viewed products. We wanted caching without mixing caching code into the repository, and we also wanted timing logs." Code public interface IProductRepository { Task<Product?> GetByIdAsync(int id, CancellationToken ct); } public sealed class SqlProductRepository(AppDbContext db) : IProductRepository { public Task<Product?> GetByIdAsync(int id, CancellationToken ct) => db.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Id == id, ct); } public sealed class CachedProductRepository(IProductRepository inner, IMemoryCache cache) : IProductRepository { public Task<Product?> GetByIdAsync(int id, CancellationToken ct) => cache.GetOrCreateAsync($"product:{id}", entry => { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5); return inner.GetByIdAsync(id, ct); }); } public sealed class LoggingProductRepository(IProductRepository inner, ILogger<LoggingProductRepository> log) : IProductRepository { public async Task<Product?> GetByIdAsync(int id, CancellationToken ct) { var started = Stopwatch.GetTimestamp(); var product = await inner.GetByIdAsync(id, ct); log.LogInformation("GetById {Id} took {Ms} ms", id, Stopwatch.GetElapsedTime(started).TotalMilliseconds); return product; } } Registration (manual wiring; the Scrutor library offers services.Decorate<,>() to do this automatically) builder.Services.AddScoped<SqlProductRepository>(); builder.Services.AddScoped<IProductRepository>(sp => new LoggingProductRepository( new CachedProductRepository(sp.GetRequiredService<SqlProductRepository>(), sp.GetRequiredService<IMemoryCache>()), sp.GetRequiredService<ILogger<LoggingProductRepository>>())); Consumers still depend only on IProductRepository; the calls now pass through logging, then caching, then SQL. Benefits - Each concern (data access, caching, logging) is in its own small, testable class. - Behaviours can be added, removed or reordered through configuration. - The same idea powers ASP.NET Core middleware and HttpClient DelegatingHandlers. Trade-offs - More classes and indirection; the order of decorators matters (logging outside the cache measures cache hits too). - Cache invalidation must be handled when products change. Other patterns you could present the same way: Strategy (interchangeable algorithms), Factory (object creation), Repository and Unit of Work (data access), Observer (events), Singleton (shared instances via DI), and Mediator (CQRS handlers).

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics