Tutorials Design Patterns in C#
Factory Method Pattern — Complete Guide
Factory Method Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 2 of 69
Factory Method Pattern
GoF Core → Enterprise → Cloud & Craft
GoF Core · 1 — Create & structure · ~6 min · Module 1: Creational Design Patterns
What is this?
Factory Method lets a creator decide which concrete product to instantiate through an overridable method — callers depend on an abstraction.
Why should you care?
ShopNest notifications switch Email vs Sms without if-else sprinkled in every controller.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public interface INotifier { void Send(string to, string body); }
public sealed class EmailNotifier : INotifier
{
public void Send(string to, string body) => Console.WriteLine($"EMAIL {to}: {body}");
}
public sealed class SmsNotifier : INotifier
{
public void Send(string to, string body) => Console.WriteLine($"SMS {to}: {body}");
}
public static class NotifierFactory
{
public static INotifier Create(string channel) => channel switch
{
"sms" => new SmsNotifier(),
_ => new EmailNotifier()
};
}
NotifierFactory.Create("sms").Send("99999", "Order shipped");
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Create returns INotifier.
- Callers never new the concrete types.
- A true GoF Factory Method often lives on a Creator subclass; this compact form shows the same idea.
Practice next
- Run the sample and try channel email vs sms.
- Add PushNotifier for channel push.
- Inject a Func
via DI later. - Throw on unknown channel instead of defaulting.
- Pass options into Create (from-address).
Remember
Create via abstraction. Centralize construction choices. Call sites stay clean.
ShopNest notify channel factory
Order events pick Email/Sms from customer preference.
Outcome: New channels plug in without editing OrderService.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!