C# Design Pattern: Decorator

Juarez Júnior - Oct 2 - - Dev Community

The Decorator pattern allows you to add new functionality to objects dynamically without modifying the original classes. It’s useful when you want to extend the functionality of an object without touching the original code or creating complex subclasses. A practical example would be a notification system where you can send notifications via email, SMS, or both, depending on how the object is decorated.

C# Code Example:

// Base component
public interface INotification
{
    void SendMessage(string message);
}

// Concrete component
public class EmailNotification : INotification
{
    public void SendMessage(string message)
    {
        Console.WriteLine($"Sending email: {message}");
    }
}

// Base decorator
public abstract class NotificationDecorator : INotification
{
    protected INotification _notification;

    public NotificationDecorator(INotification notification)
    {
        _notification = notification;
    }

    public virtual void SendMessage(string message)
    {
        _notification.SendMessage(message);
    }
}

// Concrete decorator for SMS
public class SMSNotificationDecorator : NotificationDecorator
{
    public SMSNotificationDecorator(INotification notification) : base(notification) { }

    public override void SendMessage(string message)
    {
        base.SendMessage(message);
        Console.WriteLine($"Sending SMS: {message}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Send notification via email
        INotification emailNotification = new EmailNotification();
        emailNotification.SendMessage("Hello!");

        // Send notification via email and SMS
        INotification smsAndEmailNotification = new SMSNotificationDecorator(emailNotification);
        smsAndEmailNotification.SendMessage("Hello!");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have the INotification interface, which defines the operation of sending messages. The EmailNotification class sends notifications via email, while the SMSNotificationDecorator adds the functionality to send an SMS message on top of the email. In the main code, the first notification is sent only by email, and the second is sent by both email and SMS, thanks to the decorator.

Conclusion:

The Decorator pattern allows you to add functionality to objects without altering their original classes. It’s useful for applying different functionalities in a flexible and combinable way, like in a notification system where you can add different types of alerts without modifying the main logic.

Source code: GitHub

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player