Menu

Factory Method and Simple Factory (Design Patterns)
πŸ“°

Factory Method and Simple Factory (Design Patterns)

DEV Community: dotnetΒ·DIVAKAR UPADHYAYΒ·about 15 hours ago
#IVT8hEYA
#devtodotnet#devto#dev#factory#method
Reading 0:00
15s threshold

πŸ‘‰ 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 .…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.