Decorator
- Use this pattern to add additional behavior to an object
Classical Structure

Scenario
Problem
- For every feature we are adding we need to create various classes combining these features
public class CloudStream
{
public virtual void Write(string data)
{
Console.WriteLine("Storing " + data);
}
}
public class EncryptedCloudStream: CloudStream
{
public override void Write(string data)
{
var encrypted = Encrypt(data);
base.Write(encrypted);
}
private string Encrypt(string data)
{
return "!@#$%^^&&*";
}
}
public class CompressedCloudStream: CloudStream
{
public override void Write(string data)
{
var compressed = Compress(data);
base.Write(compressed);
}
private string Compress(string data)
{
return data.Substring(0, 5);
}
}
public class CompressedAndEncryptedCloudStream: CloudStream
{
public override void Write(string data)
{
var compressed = Compress(data);
var encrypted = Encrypt(compressed);
base.Write(encrypted);
}
private string Compress(string data)
{
return data.Substring(0, 5);
}
private string Encrypt(string data)
{
return "!@#$%^^&&*";
}
}
Solution
public interface IStream
{
void Write(string data);
}
public class CloudStream: IStream
{
public virtual void Write(string data)
{
Console.WriteLine("Storing " + data);
}
}
public class CompressedCloudStream: IStream
{
private readonly IStream _stream;
public CompressedCloudStream(IStream stream)
{
_stream = stream;
}
public void Write(string data)
{
var compressed = Compress(data);
_stream.Write(compressed);
}
private string Compress(string data)
{
return data.Substring(0, 5);
}
}
public class EncryptedCloudStream: IStream
{
private IStream _stream;
public EncryptedCloudStream(IStream stream)
{
_stream = stream;
}
public void Write(string data)
{
var encrypted = Encrypt(data);
_stream.Write(encrypted);
}
private string Encrypt(string data)
{
return "!@#$%^^&&*";
}
}
public class Program
{
public static void Main()
{
var stream = new EncryptedCloudStream(new CompressedCloudStream(new CloudStream()));
stream.Write("sensitive data");
}
}
Example Structure

Example Code