Exploring the Decorator Pattern in C#

Exploring the Decorator Pattern

Having learned about the Adapter and Composite Patterns, you're well on your way to mastering structural design patterns in C#. In this lesson, we'll dive into the Decorator Pattern, another important structural pattern that allows us to add new functionalities to objects dynamically and transparently. This is particularly useful when you want to enhance the behavior of objects without modifying their code.

The Decorator Pattern enables you to wrap an object with additional behavior in a flexible and reusable way. You'll learn how to use this pattern to extend the functionality of objects in a clean and maintainable manner.

Understanding the Decorator Pattern

To understand the Decorator Pattern, let's think about a coffee shop where you can customize your coffee with various add-ons. Consider starting with a simple cup of coffee and then enhancing it with ingredients like milk, sugar, or whipped cream.

Simple Coffee (Core Component): Think of the basic coffee as the core component. It has fundamental properties, such as description and cost.

Milk (Decorator): Adding milk to the coffee decorates it with extra description ("Milk") and additional cost.

Sugar (Decorator): Similarly, adding sugar will decorate the coffee with a sugar description and additional cost.

Multiple Decorations

You can layer decorators. For instance, you can first add milk and then sugar to the already milk-decorated coffee. Each decorator wraps the core component or another decorator, adding its behavior.

Coffee simpleCoffee = new SimpleCoffee();
Coffee milkCoffee = new MilkDecorator(simpleCoffee);
Coffee milkAndSugarCoffee = new SugarDecorator(milkCoffee);

In this structure, each decorator extends the functionality of the original component dynamically. You start with a basic coffee and, by wrapping it with different decorators, you can create complex coffee orders.

Benefits of the Decorator Pattern

The Decorator Pattern allows you to dynamically add or remove functionality to objects without altering their structure. This leads to more modular and maintainable code compared to subclassing for every possible combination of enhancements. In our coffee shop example, you can easily extend the coffee's behavior at runtime by adding decorators like milk, sugar, or any other ingredients.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal