In a notification system, you might have different types of notifications such as email, SMS, and push notifications. Using the Factory Pattern, you can create a notification factory that generates the appropriate notification type based on user input.
Step 1: Define an interface for notifications.
public interface INotification
{
void Notify(string message);
}
Step 2: Implement concrete classes for each notification type.
public class EmailNotification : INotification
{
public void Notify(string message)
{
Console.WriteLine($"Sending Email: {message}");
}
}
public class SMSNotification : INotification
{
public void Notify(string message)
{
Console.WriteLine($"Sending SMS: {message}");
}
}
public class PushNotification : INotification
{
public void Notify(string message)
{
Console.WriteLine($"Sending Push Notification: {message}");
}
}
Step 3: Create a Factory class to generate the appropriate notification object.
public class NotificationFactory
{
public INotification CreateNotification(string channel)
{
if (string.IsNullOrEmpty(channel))
{
return null;
}
switch (channel.ToUpper())
{
case "EMAIL":
return new EmailNotification();
case "SMS":
return new SMSNotification();
case "PUSH":
return new PushNotification();
default:
return null;
}
}
}
Step 4: Use the Factory in the client code.
class Program
{
static void Main(string[] args)
{
NotificationFactory factory = new NotificationFactory();
INotification notification = factory.CreateNotification("EMAIL");
notification?.Notify("This is an email notification.");
notification = factory.CreateNotification("SMS");
notification?.Notify("This is an SMS notification.");
notification = factory.CreateNotification("PUSH");
notification?.Notify("This is a push notification.");
}
}