Sobes.tech
Junior — Middle

How to implement the ability to extend the functionality of the system or component?

sobes.tech AI

Answer from AI

To extend the functionality of a system or component in C#, the following approaches are often used:

  • Using interfaces and abstract classes to define extendable points.
  • Applying the "Decorator" pattern for dynamic behavior addition.
  • Using events and delegates to subscribe to changes and extend logic.
  • Dependency Injection for replacing or adding new implementations.
  • Creating a plugin architecture with assembly loading at runtime.

Example of extending functionality using an interface and the "Decorator" pattern:

public interface IMessageSender
{
    void Send(string message);
}

public class EmailSender : IMessageSender
{
    public void Send(string message)
    {
        Console.WriteLine($"Sending email: {message}");
    }
}

public class SmsSenderDecorator : IMessageSender
{
    private readonly IMessageSender _innerSender;

    public SmsSenderDecorator(IMessageSender innerSender)
    {
        _innerSender = innerSender;
    }

    public void Send(string message)
    {
        _innerSender.Send(message);
        Console.WriteLine($"Sending SMS: {message}");
    }
}

// Usage:
IMessageSender sender = new EmailSender();
sender = new SmsSenderDecorator(sender);
sender.Send("Hello!");

This approach allows adding new capabilities without modifying existing code.