Decorator Pattern in C#

Anvesh
SilentTech
Published in
3 min readAug 26, 2023

The Decorator Pattern is a structural design pattern that allows you to add new functionalities to an existing object without altering its structure.
It involves a set of decorator classes that are used to wrap concrete components.

Instead of creating distinct subclasses for each combination, you can use the Decorator Pattern to “decorate” with new functionality.

When to use the Decorator pattern?

• Large Number of Features:
Instead of having a separate subclass for each combination, you can “mix and match” with decorators.

• Single Responsibility Principle:
It allows you to divide a class that has several responsibilities into several smaller classes.

• To Avoid Modification:
If you have an existing class, and you want to add new functionalities without modifying it, then the decorator is a good choice.

  • Replacing Multiple Inheritance:
    C# doesn’t support multiple inheritance. If you’re trying to add functionalities from several sources to a single class, then using a decorator might be a good alternative.

Let’s start with a console project in c#.

First create Abstract class named Food it contains Description and Cost Methods.

Let’s Implement this Abstract Class.

Add below lines in Program.cs (I am using .NET6)

You can see the output as expected.

Now Add Cheese to our Sandwich. First create a “FoodDecorator” so we can use it to all the add-ons.

then Add our Cheese Decorator

go back to program.cs and add below lines and hit enter.

Just like Cheese we can add any other decorators.

Now let’s say you want to add Spices to sandwith, you just need one class, SpicesDecorator.

Hope you find this Article interesting for short bits around the technology follow me on LinkedIn at www.linkedin.com/in/anveshsalla

--

--

Anvesh
SilentTech

Sr. SW Engineer/ Blogger 🔔Follow me to support my journey on Medium/ 🌐LinkedIn: http://www.linkedin.com/in/anveshsalla