StructuralC#verifiedVerified

Decorator Pattern in C#

Attaches additional responsibilities to an object dynamically by wrapping it in decorator objects that share the same interface.

How to Implement the Decorator Pattern in C#

1Step 1: Define the component interface

public interface IDataSource
{
    string Read();
    void Write(string data);
}

2Step 2: Concrete component

public class FileDataSource(string filename) : IDataSource
{
    public string Read() => $"[Data from {filename}]";
    public void Write(string data) =>
        Console.WriteLine($"Writing to {filename}: {data}");
}

3Step 3: Base decorator forwards to wrapped component

public abstract class DataSourceDecorator(IDataSource source) : IDataSource
{
    public virtual string Read() => source.Read();
    public virtual void Write(string data) => source.Write(data);
}

4Step 4: Concrete decorators add behavior

public class EncryptionDecorator(IDataSource source)
    : DataSourceDecorator(source)
{
    public override string Read() =>
        $"Decrypt({base.Read()})";

    public override void Write(string data) =>
        base.Write($"Encrypt({data})");
}

public class CompressionDecorator(IDataSource source)
    : DataSourceDecorator(source)
{
    public override string Read() =>
        $"Decompress({base.Read()})";

    public override void Write(string data) =>
        base.Write($"Compress({data})");
}

// Usage:
// IDataSource source = new FileDataSource("data.txt");
// source = new EncryptionDecorator(source);
// source = new CompressionDecorator(source);
// source.Write("hello"); // Compress(Encrypt(hello))

Decorator Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Decorator Pattern in the Real World

Think of adding espresso shots and syrups to a coffee order. A plain coffee is the base component. Each addition—an espresso shot, vanilla syrup, oat milk—is a decorator that wraps the previous cup, adding its own cost and flavor. You can combine them in any order without the café needing a separate menu item for every combination.