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());
}
}
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.