Sobes.tech
Back to questions
Junior — Middle
65

Можете ли вы привести пример реализации принципа инверсии зависимостей в практике программирования?

Companies where asked
AndersenAndersen

Answer from AI

sobes.tech AI

Принцип инверсии зависимостей (Dependency Inversion Principle) заключается в том, что высокоуровневые модули не должны зависеть от низкоуровневых, а оба должны зависеть от абстракций (интерфейсов или абстрактных классов).

Пример на C#:

// Абстракция
public interface IMessageSender
{
    void Send(string message);
}

// Низкоуровневая реализация
public class EmailSender : IMessageSender
{
    public void Send(string message)
    {
        Console.WriteLine($"Отправка email: {message}");
    }
}

// Высокоуровневый модуль
public class NotificationService
{
    private readonly IMessageSender _messageSender;

    public NotificationService(IMessageSender messageSender)
    {
        _messageSender = messageSender;
    }

    public void Notify(string message)
    {
        _messageSender.Send(message);
    }
}

// Использование
var emailSender = new EmailSender();
var notificationService = new NotificationService(emailSender);
notificationService.Notify("Привет!");

Таким образом, NotificationService зависит от абстракции IMessageSender, а не от конкретной реализации EmailSender, что облегчает замену реализации и тестирование.