The Singleton design pattern ensures that a class has only one instance and provides a global access point to that instance. In C#, you can implement a Singleton pattern using lazy initialization for efficient resource usage. Here's an example of how to do it:
using System;
public class Singleton
{
    private static readonly Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton());
    // Private constructor to prevent instantiation from other classes.
    private Singleton()
    {
        Console.WriteLine("Singleton instance created.");
    }
    // Public static method to access the Singleton instance.
    public static Singleton Instance => instance.Value;
    public void SomeMethod()
    {
        Console.WriteLine("Singleton method called.");
    }
}
class Program
{
    static void Main()
    {
        // Access the Singleton instance
        Singleton singleton1 = Singleton.Instance;
        Singleton singleton2 = Singleton.Instance;
        // Verify that both instances are the same
        Console.WriteLine($"singleton1 == singleton2: {singleton1 == singleton2}");
        // Use the Singleton
        singleton1.SomeMethod();
    }
}
In this example:
- We define a - Singletonclass with a private constructor, preventing direct instantiation from other classes.
- We use - Lazy<T>to ensure lazy initialization of the Singleton instance. This means that the instance is created only when it is first accessed, improving performance and resource usage.
- The - Instanceproperty provides a static way to access the Singleton instance.
- In the - Mainmethod, we demonstrate that two calls to- Singleton.Instanceresult in the same instance being returned, confirming that it's indeed a Singleton.
Implementing the Singleton pattern with lazy initialization ensures thread safety, minimizes resource usage, and provides a single point of access to a shared instance, making it a valuable design pattern in many scenarios, such as managing application configuration, logging, and caching.
 
 
              
 
    
Top comments (0)