CodeBlanks Logo Icon CodeBlanks

Factory

C# course · Advanced · Lesson 62/83

Learn the object creation method with the Factory pattern.

Factory pattern

Factory centralizes object creation. The client does not know which concrete class is produced; it works only through an interface (INotifier). The factory method inspects a parameter, picks the right concrete type, and returns it.

The benefit: adding a new channel means changing only the factory; client code stays the same. This follows the open-closed principle: open for extension, closed for modification.

Factory method

A factory method is usually static and takes a type name as parameter. The body uses a switch expression to pick the right concrete class. The return type is the interface, so the client sees only INotifier.

Example: static INotifier Create(string type) => type switch { "sms" => new SmsNotifier(), "email" => new EmailNotifier(), _ => null };. Here _ catches the default case.

Exercise Build the NotifierFactory

Define interface INotifier with a string Send(string message) method. SmsNotifier and EmailNotifier classes implement it, returning "SMS: " + message and "Email: " + message. Inside static class NotifierFactory, a static INotifier Create(string type) method returns the right type based on type ("sms" and "email"). In Main, get a notifier with Create("sms") and print Send("Merhaba").

Show example solution
Console.WriteLine(NotifierFactory.Create("sms").Send("Merhaba"));
Example solution:
using System;

interface INotifier
{
    string Send(string message);
}

class SmsNotifier : INotifier
{
    public string Send(string message) => "SMS: " + message;
}

class EmailNotifier : INotifier
{
    public string Send(string message) => "Email: " + message;
}

static class NotifierFactory
{
    public static INotifier Create(string type) =>
        type switch
        {
            "sms" => new SmsNotifier(),
            "email" => new EmailNotifier(),
            _ => null
        };
}

class Program
{
    static void Main()
    {
        Console.WriteLine(NotifierFactory.Create("sms").Send("Merhaba"));
    }
}

Test yourself

  1. What problem does the Factory pattern solve?

    • Hides creation code
    • Picks the right concrete type at runtime
    • Forces static methods
    • Removes interfaces
    Show answer

    Picks the right concrete type at runtime — Correct. Factory inspects a parameter and picks the concrete type.

  2. Create a concrete instance

    return ____ SmsNotifier();
    Show answer
    return new SmsNotifier();
  3. Match Factory terms

    Creator
    Class hosting the factory method
    Product
    Interface of the produced object
    ConcreteProduct
    Concrete product class
    Client
    Code calling the factory

All lessons in Advanced