✏️ Explanatory Question
The Singleton pattern ensures that only one instance of a class exists throughout a session.
Implementation:
public class Singleton
{
private static Singleton instance;
private void new()
{
}
static void TypeNew()
{
instance = new Singleton();
}
public static Singleton Instance()
{
return Singleton::instance;
}
}
Explanation:
private constructor prevents external instantiation.
static instance stores the only object.
TypeNew() initializes the instance.
Instance() returns the single object.
Usage:
Singleton s = Singleton::Instance();
This guarantees controlled access and prevents multiple object creation.