Lesson 1 of 18 in the free Design Patterns (GoF + Enterprise) in C# course on DevLadder.
Ensure a class has one instance with a global access point.
// Thread-safe, lazy Singleton
public sealed class AppConfig
{
private static readonly Lazy<AppConfig> _instance = new(() => new AppConfig());
public static AppConfig Instance => _instance.Value;
private AppConfig() { /* load settings once */ }
public string ConnectionString { get; private set; } = "";
}
// Modern .NET: let the DI container own the lifetime instead
builder.Services.AddSingleton<IAppConfig, AppConfig>();
Other thread-safe options: a static readonly field (initialised by the CLR's type initialiser, thread-safe), or double-checked locking. Downsides of the hand-written pattern: global state, hidden dependencies, hard to test. Prefer AddSingleton.
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<T>: private static readonly Lazy<Svc> _i = new(() => new Svc()); public static Svc Instance => _i.Value; with a private constructor and a sealed class. Lazy<T> 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<ISvc, Svc>(). 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: Factory Method and Simple Factory →
Top comments (0)