Roadmap › Design Patterns (GoF + Enterprise) in C# › Module: Creational Patterns
Lessons in this course (18)
2. Factory Method and Simple Factory
Basic★ Must knowLesson 2 of 18
Let a method decide which concrete class to create; callers depend only on the abstraction.
csharp
public interface INotification { void Send(string to, string msg); }
public class EmailNotification : INotification { public void Send(string to, string msg) { } }
public class SmsNotification : INotification { public void Send(string to, string msg) { } }
// Simple factory
public static class NotificationFactory
{
public static INotification Create(string channel) => channel switch
{
"email" => new EmailNotification(),
"sms" => new SmsNotification(),
_ => throw new ArgumentException($"Unknown channel {channel}")
};
}
// GoF Factory Method: subclasses decide what to create
public abstract class DocumentExporter
{
protected abstract IWriter CreateWriter(); // factory method
public void Export(Doc d) { var w = CreateWriter(); w.Write(d); }
}
public class PdfExporter : DocumentExporter { protected override IWriter CreateWriter() => new PdfWriter(); }In .NET: IHttpClientFactory.CreateClient(), ILoggerFactory.CreateLogger(), DbProviderFactory.