Factory Method and Simple Factory in C#

Краткое содержание

Pixel shares a free DevLadder lesson on Factory Method and Simple Factory, with C# notification and document exporter examples. It also covers .NET factory APIs, GoF pattern categories, and interview questions, helping the community build design pattern knowledge and prepare for C# interviews.

DEV Community

Factory Method and Simple Factory (Design Patterns)

👉 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.Write(d); }
}
public class PdfExporter : DocumentExporter { protected override IWriter CreateWriter() => new PdfWriter(); }
In .NET: IHttpClientFactory.CreateClient(), ILoggerFactory.CreateLogger(), DbProviderFactory. Interview questions on Design Patterns (GoF + Enterprise) in C What are design patterns? Name the three GoF categories. Reusable, named solutions to recurring design problems. GoF (1994) lists 23 in three categories: Creational (Singleton, Factory Method, Abstract Factory, Builder, Prototype), Structural (Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy), Behavioural (Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor). How do you implement a thread-safe Singleton in C#? Use Lazy: private static readonly Lazy _i = new(() => new Svc()); public static Svc Instance => _i.Value; with a private constructor and a sealed class. Lazy is thread-safe by default (ExecutionAndPublication). Alternatives: a static readonly field (thread-safe because of the type initialiser), or double-checked locking with volatile. In ASP.NET Core, prefer services.AddSingleton(). It's testable and the container manages the lifetime. What is the difference between Factory Method and Abstract Factory? Factory Method creates one product, and subclasses (or a method) decide which concrete class to create. Abstract Factory creates a family of related products through an interface with several create methods (button + textbox for a theme; connection + command + parameter for a DB provider). Factory Method uses inheritance; Abstract Factory uses composition (you pass the factory object). Read the full lesson with progress tracking and the rest of the course on DevLadder: free step-by-step tutorials and interview questions for developers. Next in the course: Abstract Factory →
Factory Method and Simple Factory in C#
Powered by Readybot.io

Последнее от Pixel

Fix GitHub Pages: Missing Artifact Error

Pixel's announcement explains why the GitHub Pages deploy action reports that no github-pages artifact was found. It covers skipped or failed build jobs, missing uploads, …

Rotate DB and Redis Passwords Without Downtime

Pixel shares a practical guide to rotating exposed database and Redis passwords without interrupting application connections. The approach updates Secrets, changes service credentials, and gradually …

AI Agent Earns Crypto from $0: Day 3 Update

Pixel shares Day 3 of a 21-day experiment testing whether an autonomous AI agent can earn real crypto from zero. The agent launched a pay-per-call …

AI Agent Receipts Prove What Actually Executed

Pixel’s announcement examines how public Zambo receipts verify what an AI agent actually did. A BTC price fetch succeeded with a recomputable output hash, while …