在现代 .NET Core 开发中,将策略模式、工厂方法和“IEnumerable<IService>”依赖项注入相结合,可提供灵活、可缩放的解决方案。这种模式组合非常适合处理动态行为,例如在运行时选择不同的算法而不修改 core logic。
本文将通过使用不同策略(例如电子邮件、短信)发送通知的示例来分解如何实现这种方法。
1. 策略模式:封装一系列算法(或行为),并使它们在运行时可互换。每个算法都隔离在自己的类中。
Factory Method:提供一种根据运行时条件动态实例化对象的方法。
3. .NET Core 依赖项注入中的 IEnumerable<IService>:这允许将服务接口 () 的多个实现注入到类中。它提供了一种访问所有已注册实现的方法,使使用者能够迭代服务并根据特定需求选择合适的实现。IService
假设我们需要通过电子邮件、短信和推送通知等不同渠道发送通知。根据用户偏好,我们动态选择合适的策略。
public interface INotificationStrategy
{
string Key { get; } // String key to identify the strategy
void Send(string message);
}
2. 实施具体策略
public class EmailNotificationStrategy : INotificationStrategy
{
public string Key => "Email"; // Unique key for Email strategy
public void Send(string message) => Console.WriteLine($"Email sent: {message}");
}
public class SmsNotificationStrategy : INotificationStrategy
{
public string Key => "SMS"; // Unique key for SMS strategy
public void Send(string message) => Console.WriteLine($"SMS sent: {message}");
}
3. 工厂方法:使用 'IEnumerable<IService>
注入所有策略工厂在运行时使用 'IEnumerable<INotificationStrategy> 动态选择合适的策略。
public class NotificationFactory
{
private readonly IEnumerable<INotificationStrategy> _strategies;
public NotificationFactory(IEnumerable<INotificationStrategy> strategies)
{
_strategies = strategies;
}
public INotificationStrategy GetStrategy(string notificationType)
{
// Use FirstOrDefault to find the strategy by key
var strategy = _strategies.FirstOrDefault(s => s.Key == notificationType);
return strategy ?? throw new ArgumentException("Invalid notification type");
}
}
4. 在 DI 容器中
注册服务 在“Startup.cs”或任何配置服务的地方,注册所有具体策略和工厂:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<INotificationStrategy, EmailNotificationStrategy>();
services.AddTransient<INotificationStrategy, SmsNotificationStrategy>();
services.AddSingleton<NotificationFactory>();
}
5. 使用工厂的服务
public class NotificationService
{
private readonly NotificationFactory _factory;
public NotificationService(NotificationFactory factory)
{
_factory = factory;
}
public void SendNotification(string type, string message)
{
var strategy = _factory.GetStrategy(type);
strategy.Send(message);
}
}
IEnumerable<IService之前具有工厂方法的典型策略模式>
// Strategy interface
public interface INotification
{
void Send(string message);
}
// Concrete strategies
public class EmailNotification : INotification
{
public void Send(string message)
{
Console.WriteLine($"Email Notification: {message}");
}
}
public class SmsNotification : INotification
{
public void Send(string message)
{
Console.WriteLine($"SMS Notification: {message}");
}
}
// Factory for creating notifications
public static class NotificationFactory
{
public static INotification Create(string type)
{
return type switch
{
"Email" => new EmailNotification(),
"SMS" => new SmsNotification(),
_ => throw new NotImplementedException()
};
}
}
// Context class
public class NotificationService
{
private INotification _notification;
public void SetNotification(string type)
{
_notification = NotificationFactory.Create(type);
}
public void Notify(string message)
{
_notification?.Send(message);
}
}
// Client code
class Program
{
static void Main(string[] args)
{
var notificationService = new NotificationService();
// Set different notification strategies
notificationService.SetNotification("Email");
notificationService.Notify("Welcome to our service!");
notificationService.SetNotification("SMS");
notificationService.Notify("Your order has been shipped!");
}
}
在策略模式 + 工厂方法中使用在灵活性、可维护性和遵守 SOLID 原则方面具有显著优势。与传统的工厂方法方法相比,它允许动态解析策略并促进更清晰的架构,在传统的工厂方法方法中,每次添加都需要在多个位置进行更改。