📜  c# singleton - C# (1)

📅  最后修改于: 2023-12-03 14:39:44.017000             🧑  作者: Mango

C# Singleton Design Pattern

Singleton is a creational design pattern that ensures a class has only one instance while providing a global point of access to it.

Implementation

To implement a Singleton in C#, first we create a private static field to hold the instance of the class:

public class Singleton
{
    private static Singleton instance;
}

Next, we make the constructor private to prevent other classes from instantiating the Singleton class:

private Singleton() { }

Now we need a public static method to get the instance of the Singleton. This method checks if instance is null and creates a new instance if it is:

public static Singleton GetInstance()
{
    if (instance == null)
    {
        instance = new Singleton();
    }
    return instance;
}

In this implementation, instance will be created only when GetInstance() is called for the first time.

Usage

To use the Singleton, we simply call the static GetInstance() method:

Singleton singleton = Singleton.GetInstance();

If we try to create another instance using the constructor, we will get a compilation error:

Singleton singleton2 = new Singleton();  // Error: The Singleton constructor is inaccessible due to its protection level
Advantages

Using the Singleton pattern has several advantages, including:

  • It ensures that a class has only one instance, which can be useful for managing limited resources.
  • It provides a global point of access to the instance, which can simplify code and improve performance by reducing the need for parameter passing.
  • It allows the instance to be easily replaced with a subclass, which can provide alternative behavior or new features.
Conclusion

The Singleton pattern is a powerful and versatile design pattern that can improve the design and performance of your C# applications. By creating a single instance of a class and providing global access to it, you can simplify your code and improve its scalability, maintainability, and flexibility.