- The intent of this pattern is to attach additional responsibilities to an object dynamically.
- A decorator thus provides a flexible alternative to subclassing for extending functionality.
- Adding responsibility to a class can be done by adding an additional method to the class. We want to add it to an instance of the class at runtime.
namespace decoratorpattern
{
public interface IMailService
{
void sendEmail(string message);
}
public class OnPremiseEmailService : IMailService
{
public void sendEmail(string message)
{
Console.WriteLine("OnPremiseEmailService ::"+message);
}
}
public class AzureCloudEmailService : IMailService
{
public void sendEmail(string message)
{
Console.WriteLine("AzureCloudEmailService ::" + message);
}
}
//its like a base wrapper
public class MailDecoratorService : IMailService
{
private readonly IMailService _mailService;
public MailDecoratorService(IMailService mailService)
{
_mailService = mailService;
}
public virtual void sendEmail(string message)
{
_mailService.sendEmail(message);
}
}
public class AnalyticsDecoratorService : MailDecoratorService
{
public AnalyticsDecoratorService(IMailService mailService) : base(mailService)
{
}
public override void sendEmail(string message)
{
//do some extra stuff here
Console.WriteLine("inside AnalyticsDecoratorService");
base.sendEmail(message);
}
}
}
PROGRAM.CS
using decoratorpattern;
var premiseObj = new OnPremiseEmailService();
premiseObj.sendEmail("premise email service");
var azureServObj = new AzureCloudEmailService();
azureServObj.sendEmail("azure email service");
var analyticsDecObj = new AnalyticsDecoratorService(azureServObj);
analyticsDecObj.sendEmail("analyticsDecorator service");
GITHUB