Singleton — Design Patterns (GoF + Enterprise) in C#
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…
A Singleton class guarantees only one instance of itself, providing a global point of access to that instance. To ensure thread safety and lazy initialization in C#, implement a sealed class with a private constructor and a static readonly Lazy instance. The Lazy<T> class is thread-safe by default and handles both construction and publication of the instance.
Alternatives include a static readonly field for thread safety, or double-checked locking with volatile keyword for performance. In ASP.NET Core, utilize services.AddSingleton<T> to manage the Singleton's lifetime and enable testing. Factory Method and Abstract Factory are two design patterns that create objects. Factory Method defines a method within a class to return a product object, typically allowing subclasses to determine the exact concrete class to instantiate.
Abstract Factory, on the other hand, provides a set of interfaces for creating families of related or dependent objects without specifying their concrete classes, using composition instead of inheritance.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.