Singleton pattern
This pattern is a commonly used design pattern on most of the object oriented programming.
The basic idea is only one instance of a class ever exists if it is designed as singleton..
To make a class singleton the following criteria must be there.
class Singleton
{
private static Singleton instance;
// Note: Constructor is 'protected' or private
protected Singleton()
{
}
public static Singleton GetInstance()
{
// Use 'Lazy initialization'
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
static void Main()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.GetInstance();
Singleton s2 = Singleton.GetInstance();
if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}
}
This pattern is a commonly used design pattern on most of the object oriented programming.
The basic idea is only one instance of a class ever exists if it is designed as singleton..
To make a class singleton the following criteria must be there.
- Define a private
static
attribute in the “single instance” class. - Define a public
static
accessor function in the class. - Do “lazy initialization” (creation on first use) in the accessor function.
- Define all constructors to be
protected
orprivate
. - Clients may only use the accessor function to manipulate the Singleton.
class Singleton
{
private static Singleton instance;
// Note: Constructor is 'protected' or private
protected Singleton()
{
}
public static Singleton GetInstance()
{
// Use 'Lazy initialization'
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
static void Main()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.GetInstance();
Singleton s2 = Singleton.GetInstance();
if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}
}
No comments:
Post a Comment