控制反转 (inversion of control)

时间:2023-03-09 18:02:16
控制反转 (inversion of control)

The inversion of control (IoC) pattern is abstract; it says that one should move dependency creation
out of the consumer class, but it doesn’t talk about exactly how to achieve that.

public class EmailService
{
public void SendMessage() { ... }
}
public interface IMessagingService
{
void SendMessage();
}
public class EmailService : IMessagingService
{
public void SendMessage() { ... }
}
public class NotificationSystem
{
private IMessagingService svc;
public NotificationSystem()
{
svc = new EmailService();
}
public void InterestingEventHappened()
{
svc.SendMessage();
}
}