dimanche 14 novembre 2021

Implement two notification systems for an event with Strategy pattern

I have a list of subscribes in my database

Subscriber:
string Name      <- required
string Phone     <- required
string EventName <- required
string Email     <- optional 

The subscriber can subscribe on some event by its name (EventName).

When an event occurs, I need to send a notification to all subscribers (where EventName==the event which occurred) via Email or SMS. If Email is not null, then send email. If Email is null, send SMS to Phone.

I my business logic I created this abstraction:

public interface INotification
{
   Task Send(string message, IEnumerable<Subscriber> subscribers);
}

and use it in event handler

var subscribes = _db.Subscribers.Where(x => x.EventName == event);
await _notification.Send(message, subscribes);

Then I'm going to use a Strategy pattern.

public interface INotificationStartegy
{
   Task Send(string message, string to);
}
public interface EmailNotificationStartegy : INotificationStartegy
{
   /// 
}
public interface SmsNotificationStartegy : INotificationStartegy
{
   /// 
}

Here is an example of INotification implementation

public class Notification : INotification
{
  public Notification(SmsNotificationStartegy smsSender, EmailNotificationStartegy emailSender) =>
     (_smsSender, _emailSender);

  public async Task Send(string message, IEnumerable<Subscriber> subscribers)
  {   
    foreach(Subscriber sub in subscribers)
    {
        if (!string.IsNullOrEmpty(sub.Email)
        {
            await _emailSender.Send(message, sub.Email);
        } else {
            await _smsSender.Send(message, sub.Phone);
        }
    }
  }
}

Could you please suggest if it is a proper way to use Strategy? I thought the Strategy pattern can help us to avoid if/switch in a code, but who will decide what strategy to use then? I'm confused, do I really need this INotification abstraction or can I use that forearch directly in my event handler?

Could anyone explain benefits of INotification? Or is it a wrong implementation?

What if I need to add one more strategy, I should always modify Notification? Are there any ways how to avoid it?

Aucun commentaire:

Enregistrer un commentaire