Design Patterns

Example 2. Text Formatting in a Word Processor

Imagine a text formatting module in a word processor where you can apply various formatting options like bold, italic, and underline using the Decorator Pattern:


using System;

// Component Interface
public interface IText
{
    string GetText();
}

// Concrete Component
public class PlainText : IText
{
    private string _text;

    public PlainText(string text)
    {
        _text = text;
    }

    public string GetText()
    {
        return _text;
    }
}

// Decorator
public abstract class TextDecorator : IText
{
    protected IText _text;

    public TextDecorator(IText text)
    {
        _text = text;
    }

    public virtual string GetText()
    {
        return _text.GetText();
    }
}

// Concrete Decorators
public class BoldDecorator : TextDecorator
{
    public BoldDecorator(IText text) : base(text) { }

    public override string GetText()
    {
        return "" + base.GetText() + "";
    }
}

public class ItalicDecorator : TextDecorator
{
    public ItalicDecorator(IText text) : base(text) { }

    public override string GetText()
    {
        return "" + base.GetText() + "";
    }
}

public class UnderlineDecorator : TextDecorator
{
    public UnderlineDecorator(IText text) : base(text) { }

    public override string GetText()
    {
        return "" + base.GetText() + "";
    }
}

// Client Code
public class Program
{
    public static void Main(string[] args)
    {
        // Create a plain text
        IText plainText = new PlainText("Hello, Decorator Pattern!");

        // Decorate with bold and italic
        IText decoratedText = new BoldDecorator(new ItalicDecorator(plainText));

        Console.WriteLine(decoratedText.GetText());
    }
}

  • Component Interface (IText): Defines a method for getting text.
  • Concrete Component (PlainText): Represents plain text.
  • Decorator (TextDecorator): Abstract class that implements IText and holds a reference to IText.
  • Concrete Decorators (BoldDecorator, ItalicDecorator, UnderlineDecorator): Extend TextDecorator to add HTML tags for bold, italic, and underline formatting.
  • Client Code: Demonstrates how decorators (BoldDecorator, ItalicDecorator) are applied to a PlainText object to apply text formatting.
Summary

Overall, the Decorator Pattern provides a flexible and modular approach to extending object behavior, making it particularly suitable for scenarios where objects require dynamic, incremental enhancements or where a high degree of customization is needed without altering existing code.