Wednesday, April 16, 2025

Design pattern /SOLID

Factory Method /Liskov Substitution Principle:

----Creates an instance of several derived classes

The Factory Method is one of the classic Creational Design Patterns — and it's perfect when you need to delegate the responsibility of object creation to subclasses, without specifying the exact class.

--------------

"Objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program."

In simple terms:

If class B is a subclass of class A, then I should be able to use B anywhere I use A — without breaking stuff.

----------------------------

1.Product Interface 

public interface INotification

{

    void Send(string message);

}

2. Concrete implementations
public class EmailNotification : INotification
{
    public void Send(string message)
    {
        Console.WriteLine($"Sending Email: {message}");
    }
}

public class SmsNotification : INotification
{
    public void Send(string message)
    {
        Console.WriteLine($"Sending SMS: {message}");
    }
}

3. Factory (Creator)

public abstract class NotificationFactory
{
    public abstract INotification CreateNotification();
}
or 
public interface  INotificationFactory
{
    public INotification CreateNotification();
}


4.

public class EmailNotificationFactory : NotificationFactory
{
    public override INotification CreateNotification()
    {
        return new EmailNotification();
    }
}

public class SmsNotificationFactory : NotificationFactory
{
    public override INotification CreateNotification()
    {
        return new SmsNotification();
    }
}

or 
public class EmailNotificationFactory : INotificationFactory
{
    public INotification CreateNotification()
    {
        return new EmailNotification();
    }
}

public class SmsNotificationFactory : NotificationFactory
{
    public INotification CreateNotification()
    {
        return new SmsNotification();
    }
}

-------------main----Client End Code------------
INotification notification = new EmailNotification();
notification.Send("Welcome!");

dynamically via the factory:

NotificationFactory factory = new EmailNotificationFactory(); INotification notification = factory.CreateNotification(); notification.Send("Hi there!");

or
INotificationFactory factory = new EmailNotificationFactory(); INotification notification = factory.CreateNotification(); notification.Send("Hi there!");

No comments:

Post a Comment