The Decorator and Proxy design patterns are two patterns that are often confused with each other.
And honestly, the confusion is understandable.
Both patterns wrap another object. Both implement the same interface as the object they wrap. And both can execute code before or after calling the wrapped object.
So if they look almost identical in code, what actually makes them different?
The main difference is their intent.
A Decorator adds behavior to an object, while a Proxy controls access to an object.
The implementation can look very similar, but the reason you introduce the wrapper is different.
First, what problem are we trying to solve?
Imagine we have a simple service:
public interface IOrderService
{
Task<Order> GetOrderAsync(Guid id);
}And an implementation:
public class OrderService : IOrderService
{
public async Task<Order> GetOrderAsync(Guid id)
{
// Retrieve order
return await GetFromDatabaseAsync(id);
}
}Over time, we may want to add logging, caching, authorization, metrics, retry policies, or other behavior.
One option would be to put everything inside OrderService:
public async Task<Order> GetOrderAsync(Guid id)
{
LogRequest(id);
CheckAuthorization();
if (cache.TryGetValue(id, out Order? cachedOrder))
return cachedOrder;
var order = await GetFromDatabaseAsync(id);
cache.Set(id, order);
RecordMetric();
return order;
}The service now knows about database access, caching, authorization, logging, and metrics.
This is where wrapping becomes useful.
The Decorator Pattern
The Decorator pattern allows us to wrap an object and add responsibilities to it without modifying the original implementation.
Let's say we want to add caching.
We can create a decorator:
public class CachedOrderService : IOrderService
{
private readonly IOrderService orderService;
private readonly IMemoryCache cache;
public CachedOrderService(
IOrderService orderService,
IMemoryCache cache)
{
orderService= orderService;
cache = cache;
}
public async Task<Order> GetOrderAsync(Guid id)
{
if (cache.TryGetValue(id, out Order? order))
return order!;
order = await orderService.GetOrderAsync(id);
cache.Set(id, order);
return order;
}
}The caller doesn't need to know that caching exists.
It simply calls:
await orderService.GetOrderAsync(orderId);The decorator intercepts the call, performs its additional behavior, and delegates the actual operation to the wrapped service.
For example:
public class LoggingOrderService : IOrderService
{
private readonly IOrderService orderService;
private readonly ILogger<LoggingOrderService> logger;
public LoggingOrderService(
IOrderService orderService,
ILogger<LoggingOrderService> logger)
{
orderService = orderService;
logger = logger;
}
public async Task<Order> GetOrderAsync(Guid id)
{
logger.LogInformation(
"Getting order {OrderId}",
id);
var result = await orderService.GetOrderAsync(id);
logger.LogInformation(
"Order {OrderId} retrieved",
id);
return result;
}
}
Join the conversation! Your thoughts help the community grow.