C# Singleton Pattern: Implementation Guide
In C#, you can use the following method to implement the singleton design pattern:
- Create a static method for accessing a singleton instance, typically named GetInstance() or Instance().
- In this approach, a static variable is used to store the singleton instance and it is initialized on the first call to the method.
- Ensure that the constructor is private in order to prevent direct instantiation of objects from outside.
- Use this static method to obtain a singleton instance and call it wherever necessary.
Here is a simple example code:
public class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton GetInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
public void DoSomething()
{
Console.WriteLine("Doing something...");
}
}
class Program
{
static void Main()
{
Singleton singleton = Singleton.GetInstance();
singleton.DoSomething();
}
}
In the above example, we obtain an instance of the Singleton class by calling the GetInstance() method and then perform operations by calling the DoSomething() method. It is important to note that since the constructor is private, the Singleton object cannot be directly instantiated from outside.