Decorator: Extending Object Behaviour Without Changing Its Class
Design Patterns Explained: From Theory to Practice: Article 10
As applications grow, existing components often need additional functionality.
In a ticket-management application, for example, we might initially have a service responsible for sending email notifications when tickets are assigned.
Over time, new requirements appear. We want to log notification activity, include ticket references in outgoing messages, record delivery information and perhaps add other optional behaviours.
One approach is to create new subclasses for every combination of functionality. We could end up with classes such as "LoggedEmailNotificationSender", "AuditedEmailNotificationSender" and "LoggedAndAuditedEmailNotificationSender".
If we introduce another notification transport, such as SMS, the number of possible combinations grows even further.
This is where the Decorator pattern becomes useful.
Instead of repeatedly extending the original class through inheritance, we can wrap an existing object with another object that implements the same interface and adds specific behaviour.
What is the Decorator pattern?
Decorator is a structural design pattern that allows us to attach additional responsibilities to an object dynamically, without modifying its underlying class.
The key idea is that a decorator implements the same interface as the object it wraps.
From the client's perspective, the decorated object is still the same type of component. However, its behaviour has been extended.
Multiple decorators can also be wrapped around the same object, allowing us to combine different responsibilities without creating a separate subclass for every combination.
For example, our email notification sender could be wrapped with a decorator that adds a ticket reference to the message, followed by another decorator that logs the notification activity.
The result is a stack of objects that work together while exposing the same interface to the client.
This is why Decorator is also commonly known as the Wrapper pattern.
Understanding the participants
The Decorator pattern has five main participants:
Participant| Responsibility
Component| Defines the common interface shared by the original object and its decorators.
Concrete Component| Provides the original functionality that can be extended.
Base Decorator| Implements the component interface and holds a reference to another component, delegating operations to it.
Concrete Decorator| Adds specific responsibilities before or after delegating to the wrapped component.
Client| Uses the component interface without needing to know whether the object is decorated.
In our ticket-management example:
- Component: "ITicketNotificationSender" defines the notification-sending operation.
- Concrete Component: "EmailTicketNotificationSender" provides the basic email notification functionality.
- Base Decorator: "TicketNotificationSenderDecorator" holds and delegates to another "ITicketNotificationSender".
- Concrete Decorators: "LoggingTicketNotificationDecorator" and "TicketReferenceFooterDecorator" add optional behaviours.
- Client: "TicketAssignmentService" sends notifications through the common interface.
The important detail is that decorators and the original component share the same interface. This allows us to wrap an object multiple times without changing how the client interacts with it.
Implementing Decorator in C#
Let's implement this using our ticket-management application.
Our requirement is to send email notifications when tickets are assigned, while allowing additional functionality to be introduced independently of the underlying email sender.
We'll implement two decorators:
1. "TicketReferenceFooterDecorator" adds the ticket reference to the notification message.
2. "LoggingTicketNotificationDecorator" records when a notification is being sent and when the operation completes.
1. Define the component interface and notification model
We start with a simple notification model.
public sealed record TicketNotification(
string TicketReference,
string Recipient,
string Subject,
string Message);
Next, we define the component interface.
public interface ITicketNotificationSender
{
Task SendAsync(
TicketNotification notification,
CancellationToken cancellationToken);
}
This interface represents the operation that every notification sender and decorator must support.
The use of an interface is important because it allows the client to depend on an abstraction rather than a specific notification implementation.
2. Create the concrete component
Our concrete component provides the basic functionality: sending an email notification.
For this example, we'll depend on an "IEmailClient" abstraction that represents the underlying email delivery mechanism.
public interface IEmailClient
{
Task SendAsync(
string recipient,
string subject,
string body,
CancellationToken cancellationToken);
}
Now we implement the actual notification sender.
public sealed class EmailTicketNotificationSender
: ITicketNotificationSender
{
private readonly IEmailClient _emailClient;
public EmailTicketNotificationSender(
IEmailClient emailClient)
{
_emailClient = emailClient;
}
public Task SendAsync(
TicketNotification notification,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(notification);
return _emailClient.SendAsync(
notification.Recipient,
notification.Subject,
notification.Message,
cancellationToken);
}
}
This class has one responsibility: translating our ticket notification into an email delivery request.
It does not need to know anything about logging, auditing or additional message formatting.
That separation is intentional. We want the original component to remain focused on its core functionality.
3. Create the base decorator
Next, we create the base decorator.
public abstract class TicketNotificationSenderDecorator
: ITicketNotificationSender
{
protected ITicketNotificationSender Inner { get; }
protected TicketNotificationSenderDecorator(
ITicketNotificationSender inner)
{
Inner = inner
?? throw new ArgumentNullException(nameof(inner));
}
public virtual Task SendAsync(
TicketNotification notification,
CancellationToken cancellationToken)
{
return Inner.SendAsync(
notification,
cancellationToken);
}
}
There are two important details here.
First, the base decorator implements the same "ITicketNotificationSender" interface as the original component.
Second, it holds a reference to another "ITicketNotificationSender", rather than depending directly on "EmailTicketNotificationSender".
This means the decorator can wrap any implementation of the interface, including another decorator.
The default implementation simply delegates the operation to the wrapped object.
Concrete decorators can then override this method to introduce additional behaviour.
4. Create the concrete decorators
Now we can implement our additional functionality.
TicketReferenceFooterDecorator
The first decorator adds the ticket reference to the bottom of the notification message.
public sealed class TicketReferenceFooterDecorator
: TicketNotificationSenderDecorator
{
public TicketReferenceFooterDecorator(
ITicketNotificationSender inner)
: base(inner)
{
}
public override Task SendAsync(
TicketNotification notification,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(notification);
TicketNotification updatedNotification =
notification with
{
Message =
$"{notification.Message}" +
$"{Environment.NewLine}{Environment.NewLine}" +
$"Ticket reference: {notification.TicketReference}"
};
return Inner.SendAsync(
updatedNotification,
cancellationToken);
}
}
Notice that the decorator does not send the email itself.
Instead, it modifies the notification and delegates the operation to the wrapped component.
The underlying email sender remains completely unaware that the message has been extended.
Also notice that the method returns the inner "Task" directly rather than using "async" and "await". There is no additional asynchronous work to perform in this decorator, so introducing an asynchronous state machine would provide no benefit.
LoggingTicketNotificationDecorator
Our second decorator adds logging around the notification operation.
public sealed class LoggingTicketNotificationDecorator
: TicketNotificationSenderDecorator
{
private readonly ILogger<LoggingTicketNotificationDecorator>
_logger;
public LoggingTicketNotificationDecorator(
ITicketNotificationSender inner,
ILogger<LoggingTicketNotificationDecorator> logger)
: base(inner)
{
_logger = logger;
}
public override async Task SendAsync(
TicketNotification notification,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(notification);
_logger.LogInformation(
"Sending notification for ticket {TicketReference} to {Recipient}",
notification.TicketReference,
notification.Recipient);
await Inner.SendAsync(
notification,
cancellationToken);
_logger.LogInformation(
"Notification sent successfully for ticket {TicketReference}",
notification.TicketReference);
}
}
This decorator logs the beginning and successful completion of the operation.
If the underlying operation fails, the exception propagates to the caller. The decorator does not silently swallow it or change the original error-handling contract.
We now have two independent decorators, each adding a specific responsibility without modifying the original email sender.
5. Combine the decorators
The real benefit of the pattern becomes clearer when we combine multiple decorators.
ITicketNotificationSender sender =
new LoggingTicketNotificationDecorator(
new TicketReferenceFooterDecorator(
new EmailTicketNotificationSender(emailClient)),
logger);
The resulting structure looks like this:
LoggingTicketNotificationDecorator
|
TicketReferenceFooterDecorator
|
EmailTicketNotificationSender
When the client calls "SendAsync()", the operation passes through the decorators.
1. The logging decorator records that a notification is being sent.
2. The footer decorator adds the ticket reference to the message.
3. The email sender delivers the updated notification.
4. Control returns through the decorators, allowing the logging decorator to record successful completion.
The order of decorators matters because each one can modify or observe the operation before delegating to the next component.
We could also use the email sender without either decorator, or wrap it with only one of them.
The original component does not need to change in any of these scenarios.
6. Use the decorated component
Finally, our application service can depend entirely on "ITicketNotificationSender".
public sealed class TicketAssignmentService
{
private readonly ITicketNotificationSender _notificationSender;
public TicketAssignmentService(
ITicketNotificationSender notificationSender)
{
_notificationSender = notificationSender;
}
public Task NotifyAssigneeAsync(
TicketNotification notification,
CancellationToken cancellationToken)
{
return _notificationSender.SendAsync(
notification,
cancellationToken);
}
}
The service does not know whether it is using a basic email sender, a decorated email sender or another notification implementation.
It simply calls "SendAsync()".
This is the central benefit of Decorator: we can extend an object's behaviour without modifying the original class or changing the interface expected by its clients.
When should you use the Decorator pattern?
Decorator is useful when you need to add optional responsibilities to existing objects without creating an increasingly complicated inheritance hierarchy.
Consider using it in the following situations:
1. When you need to add behaviour dynamically
If different parts of an application require different combinations of functionality, decorators allow you to compose those combinations at runtime.
For example, one notification sender might require logging and message enrichment, while another only needs logging.
2. When several independent responsibilities need to be combined
If a class is accumulating unrelated responsibilities, decorators can help separate them into focused components.
Logging, caching, validation, compression and message enrichment are examples of behaviour that can sometimes be implemented through decorators.
3. When inheritance creates too many subclasses
If you find yourself creating subclasses for every possible combination of features, consider whether those features could instead be implemented as independent decorators.
This can reduce the number of concrete classes and make functionality easier to combine.
However, Decorator is not automatically the right solution whenever a class needs additional behaviour.
If a feature is fundamental to an object's identity or must always be present, implementing it directly in the component may be simpler.
The additional flexibility is valuable only when the application genuinely benefits from being able to compose or remove responsibilities independently.
Advantages and trade-offs
Like the other patterns in this series, Decorator offers flexibility but also introduces additional design considerations.
Advantages
- Open/Closed Principle: Existing classes can remain unchanged while new behaviour is introduced through additional decorators.
- Single Responsibility Principle: Each decorator can focus on a specific responsibility rather than allowing one class to accumulate unrelated functionality.
- Runtime flexibility: Decorators can be combined in different configurations depending on application requirements.
- Avoids subclass proliferation: Multiple behaviours can be composed without creating a separate subclass for every combination.
- Reusability: The same decorator can be applied to different concrete implementations as long as they implement the same component interface.
Disadvantages
- Additional objects and indirection: Each decorator introduces another layer through which operations must pass.
- Debugging can become more difficult: A failure may originate in one of several decorators, making the execution flow harder to follow.
- Order can matter: Some decorators depend on the order in which they are applied, particularly when they modify data or operation results.
- Configuration can become complicated: Constructing and maintaining long decorator chains can make application setup harder to understand.
- Removing a specific decorator can be difficult: Once objects have been composed into a nested wrapper structure, changing the configuration may require rebuilding the chain.
The goal is to keep each decorator focused and avoid introducing layers that provide little practical value.
Decorator in modern .NET applications
Decorator is a design pattern rather than a feature of the .NET dependency injection container.
However, dependency injection makes it easier to manage decorator construction and provide the dependencies required by each layer.
One option is to construct the decorator chain manually using a factory or a registration delegate.
Another option is to use Scrutor, a library that extends "IServiceCollection" with service registration and decoration capabilities.
After installing the Scrutor NuGet package, we can register our notification sender and apply decorators:
builder.Services.AddTransient<
ITicketNotificationSender,
EmailTicketNotificationSender>();
builder.Services.Decorate<
ITicketNotificationSender,
TicketReferenceFooterDecorator>();
builder.Services.Decorate<
ITicketNotificationSender,
LoggingTicketNotificationDecorator>();
The registrations are applied in sequence. The last decorator registered becomes the outermost layer.
The resulting structure is:
LoggingTicketNotificationDecorator
|
TicketReferenceFooterDecorator
|
EmailTicketNotificationSender
The dependency injection container resolves the required constructor dependencies, including "IEmailClient" and "ILogger<T>".
The application still needs to register its email client implementation and any other dependencies.
Service lifetimes also need to be considered carefully. The wrapped service and its decorators should use compatible lifetimes so that scoped dependencies are not accidentally captured by longer-lived services.
Scrutor is an optional library rather than part of the built-in .NET service container. The underlying Decorator pattern can be implemented perfectly well without it.
Decorator vs. Adapter, Proxy and Composite
Decorator is sometimes confused with other structural patterns because they can all involve one object holding a reference to another.
However, their intentions are different.
Pattern| Primary intention| Typical question
Adapter| Converts an existing interface into another interface expected by a client.| How can these incompatible components work together?
Decorator| Adds responsibilities to an object while preserving its interface.| How can I extend this object's behaviour without changing its class?
Proxy| Controls access to another object while preserving its interface.| How can I control access to this object?
Composite| Organises individual objects and groups into a tree structure that clients can treat uniformly.| How can I treat an individual object and a group of objects in the same way?
The distinction between Decorator and Proxy is particularly important.
Both can implement the same interface as the object they wrap. However, a Proxy primarily controls access to the underlying object, perhaps through lazy initialisation, access checks or remote communication.
A Decorator, on the other hand, adds responsibilities to the object.
Decorator and Composite also have similar structures because both use composition. The key difference is that Composite organises multiple child components into a hierarchy, while a decorator typically wraps one component to extend its behaviour.
These patterns can even work together. For example, we could use a decorator to add logging to a particular component within the ticket hierarchy introduced in the previous article.
Conclusion
Decorator is useful when an application needs to extend existing functionality without repeatedly modifying classes or creating subclasses for every possible combination of behaviour.
By wrapping an object with another implementation of the same interface, we can add responsibilities independently and combine them at runtime.
However, the pattern introduces additional layers and requires careful management of their order and configuration.
It is most valuable when the additional flexibility makes the application easier to extend and maintain.
As with the other patterns in this series, the objective is not to introduce abstractions simply because they are available. It is to choose a design that solves a genuine problem without making the application unnecessarily complicated.
In the next article, we'll explore Facade, a pattern that provides a simpler interface for interacting with complex subsystems.
Further reading
- Dive Into Design Patterns — Alexander Shvets. See the Structural Design Patterns chapter on Decorator.
- Design Patterns in C#, Second Edition — Vaskaran Sarcar. See Chapter 7, Decorator Pattern.
- "Refactoring.Guru — Decorator" (https://refactoring.guru/design-patterns/decorator)
- "Microsoft Learn — Dependency injection in .NET" (https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection)
- "Scrutor — Assembly scanning and decoration for .NET" (https://github.com/khellang/Scrutor)
Comments
Join the discussionNo comments yet. Be the first to comment.