Reputation: 610
I am trying to understand singleton pattern in C#. I got 1 structure for that but i have some doubt in the implementation. Since I'm new to C#, i want to know how this is working.
public class Class1
{
public static void Main(string[] args)
{
Singleton.Object.Func1();
}
}
public sealed class Singleton
{
private static readonly Singleton _obj = new Singleton();
static Singleton() { } // Make sure it's truly lazy
private Singleton() { } // Prevent instantiation outside
public static Singleton Object { get { return _obj; } }
public void Func1() { }
}
Is this pattern correct for a singleton class?
What is the purpose of this line "static Singleton() { } // Make sure it's truly lazy"
How the class identify only 1 instance is created in a particular time
Upvotes: 0
Views: 152
Reputation: 1146
Note that:
A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
The singleton pattern is commonly used when you only want one instance of your class to be created. For example you might want to have an InputManager class who deals will processing all of the mouse and keyboard events for your engine. It doesn't make sense to have multiple instances of this class because then you would have to keep multiple copies of the manager up to date and then determine whose job it is to process the event. Instead you can use a singleton to make sure that input is all dealt with by the one manager.
Upvotes: 1
Reputation: 1797
Your pattern is valid. There are some other ways to do it but this is fine.
static Singleton() { }
I don't believe is necessary but I could be wrong, it's more akin to something you need to do in C++ to make sure when you call for it, it grabs the singleton.
As _obj is static, the class can only have 1 version of it at any given time, meaning whenever you call it with .Object, it returns this one valid copy.
Upvotes: 3