Design Pattern articles in this series are listed below:

Design Patterns - An Overview
Design Patterns – Using the Strategy Pattern in C#
Design Patterns – Using the Singleton Pattern in C#
Design Patterns – Using the Adapter Pattern in C#
Design Patterns - Using the Facade Pattern in C#
Design Patterns - Using the Composite Pattern in C#
Design Patterns - Using the Decorator Pattern in C#
Design Patterns - Using the Abstract Factory Pattern in C#
Design Patterns – Using the Builder Pattern in C#
Design Patterns - Using the Observer Pattern in C# (Events and Delegates)
Design Patterns – Using the Chain of Responsibility Pattern in C#
Design Patterns – Using the State Pattern in C#
Design Patterns – Which to use When? Take the Quiz!

What is a Decorator Pattern?

Decorator Patterns belong to the Structural Pattern category and it’s role is in providing a way of attaching new behavior to the object at run time. The object is unaware of the new behavior and this pattern is a good candidate for enhancing legacy applications. Decorator Pattern provides a way of adding functionality to an existing class without using inheritance.

A key characteristic of Structural Patterns is that they can be used not only during the creation of a system but also during maintenance and enhancements. Since the Decorator pattern allows us to extend the behavior of an instance of a class rather than the class itself, the underlying class remains untouched.

How is the Decorator Pattern implemented?

The essential players in the Decorator Pattern are:

1. Component – This is the original class implementation

2. IComponent – The interface that identifies the class of objects that can be decorated

3. Decorator Base Class – The base class for decorator concrete classes

4. Decorator Concrete Class(es) – One or more classes that provide the implementation for the Decorators.

5. Client – A consumer class

Let us implement the Decorator pattern with an example. Let us assume we are maintaining an application for a car manufacturing company. When the application was created, the company manufactured only one type of car – the Boring car. The implementation of the Boring car class is as shown below.

public interface ICar
{
    string Description { get; }
    int Price { get; }
}

public class BoringCar : ICar
{
    public string Description
    {
        get
        {
            return "Boring Car";
        }
    }

    public int Price
    {
        get
        {
            return 20000;
        }
    }
}