Decorator pattern is using when you want to extend existing class behavior without it’s changing and without inheritance. Let’s pretend that we have an object and we use to extend its capabilities. And we can’t change current class code or we don’t have access to source code of this class.

For example, I want to create simple Html Builder, that can be extension of StringBuilder. As result of this code, should be next.

HtmlBuilder hb = new HtmlBuilder();
hb.AppendLine("Example")
  .AppendHtmlObject("Body", "Contents");

Console.WriteLine(hb.ToString());
Console.ReadLine();

To realize this logic scheme, let’s create HtmlBuilder class, that will extent StringBuilder class. Also I used fluent interface.

public class HtmlBuilder
{
    private StringBuilder stringBuilder = new StringBuilder();

    public HtmlBuilder AppendLine(string s)
    {
        stringBuilder.AppendLine(s);
        return this;
    }

    public HtmlBuilder AppendHtmlObject(string tagName, string value)
    {
        stringBuilder.AppendLine($"<{tagName}>"); ;
        stringBuilder.AppendLine($"    {value}"); ;
        stringBuilder.AppendLine($"<</{tagName}>"); ;
        return this;
    }

    public override string ToString()
    {
        return stringBuilder.ToString();
    }
}