π Full lesson with practice questions on DevLadder (free, lesson 2 of 18 in the Design Patterns (GoF + Enterprise) in C# course)
Let a method decide which concrete class to create; callers depend only on the abstraction.
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 .β¦