Example
public interface IDataSource
{
void WriteData(string data);
string ReadData();
}
public class FileDataSource(string fileName) : IDataSource
{
public void WriteData(string data) { ... }
public string ReadData() { ... }
}
public class EncryptionDecorator(IDataSource wrapped) : IDataSource
{
public void WriteData(string data) => wrapped.WriteData(Encrypt(data));
public string ReadData() => Decrypt(wrapped.ReadData());
private string Encrypt(string data) { ... }
private string Decrypt(string data) { ... }
}
… where we can have other decorators, e.g., CompressionDecorator. Usage is
of the form:
IDataSource source = new FileDataSource("data.txt");
source = new EncryptionDecorator(source);
source = new CompressionDecorator(source);
source.WriteData("Sensitive info");
Use Case
When you need to layer on extra functionality at runtime based on conditions, e.g., encrypt certain messages, wrap a service with logging in debug mode, etc.
Consider a Window in a windowing system. To allow scrolling on some Window
objects, one could either create a ScrollingWindow subclass, or create a
ScrollingWindowDecorator that adds this functionality to existing Window
objects. Suppose you then want to support adding borders to some Window
objects. If continuing with sub-classing, then we’d have WindowWithBorder,
ScrollingWindowWithBorder, etc. Compare that to having a
BorderedWindowDecorator, where any combination of ScrollingWindowDecorator
or BorderedWindowDecorator can decorate existing Windows. If the
functionality needs to be added to all Windows, the base class can be
modified. However, sometimes modifying the base class is not possible, e.g.,
using an external framework where it’s not possible/legal to modify the base
class.
References
- Design Patterns | Hello Interview Low Level Design. www.hellointerview.com . Accessed Oct 3, 2026.
- Decorator pattern - Wikipedia. en.wikipedia.org . Accessed Oct 3, 2026.