The Factory Design Pattern in C# is a creational design pattern that provides an interface for creating objects in a superclass while allowing subclasses to alter the types of objects that are created. This pattern encapsulates object creation logic, decoupling it from the client code that uses the objects.
It is beneficial for situations requiring flexibility, such as adding new product types without modifying existing client code.
When to use the Factory pattern?
- Uncertainty about object type: When a class cannot predict the type of objects it needs to create, and this decision is better made at runtime.
- Subclasses decide instantiation: When you want to delegate the responsibility of creating objects to subclasses, allowing them to alter the type of objects created.
- Encapsulating creation logic: When the process of creating an object is complex, repetitive, or has many dependencies, the factory pattern can encapsulate this logic, making the code cleaner.
- Extending with new products: When you want to easily add new product types in the future. Instead of modifying the client code, you can simply create a new subclass and implement its creation logic within the factory.
- Decoupling client from concrete classes: To decouple the client code from the concrete classes it instantiates. The client only interacts with the factory and a common interface, not the specific implementations.
Bad Example: Notification System.
if (notification == "Email") new EmailNotification(); else if (notification == "SMS") new SMSNotification(); else if (notification == "PUSH") new PUSHNotification();
Good Example: Notification System Using Factory Method.
public interface INotification { void Send(string to, string message); }
public class EmailNotification : INotification { public void Send(string to, string message) { Console.WriteLine($"Sending Email to {to} : {message}"); } } public class SMSNotification : INotification { public void Send(string to, string message) { Console.WriteLine($"Sending SMS to {to} : {message}"); } } public class PUSHNotification : INotification { public void Send(string to, string message) { Console.WriteLine($"Sending PUSH to {to} : {message}"); } }
public abstract class NotificationFactory { public abstract INotification CreateNotification(); }
public class EmailFactory : NotificationFactory { public override INotification CreateNotification() { return new EmailNotification(); } } public class SMSFactory : NotificationFactory { public override INotification CreateNotification() { return new SMSNotification(); } } public class PUSHFactory : NotificationFactory { public override INotification CreateNotification() { return new PUSHNotification(); } }
NotificationFactory factory; factory = new EmailFactory(); var email = factory.CreateNotification(); email.Send("user@example.com", "Welcome Email!");
new calls, simplify object creation, and extend your application without modifying existing code.





