Singleton Pattern ensures that a class has only one
instance and provides a global point of access to it.
Sample code:
Create a Singleton Class with a private static object of itself. Create a constructor (either private or protected). Create a static method that returns an object of itself (Singleton class).
Sample code:
Create a Singleton Class with a private static object of itself. Create a constructor (either private or protected). Create a static method that returns an object of itself (Singleton class).
In
Main, create 2 objects of Singleton class by calling static method created
above. If you compare both objects, they are same.
In
this way a singleton pattern can be applied so as to create a single instance
of a class.
For
more clarification, add a public string field in Singleton class. In the Main
Method, assign value to string field for both objects. Now write the value of
the string field to console. The string field contains the same value which is
assign at last.
Singleton
provides a global, single instance by:
- Making the class create a single instance of itself.
- Allowing other objects to access this instance through a class method that returns a reference to the instance. A class method is globally accessible.
- Declaring the class constructor as private so that no other object can create a new instance.
Code:
class SingletonClass
class SingletonClass
{
private static SingletonClass _instance;
public string
strName;
protected SingletonClass
()
{
}
/*private SingletonClass ()
// Any one private or protected constructor
{
} */
public static SingletonClass Instance()
{
if (_instance == null)
_instance = new SingletonClass();
return _instance;
}
static void Main(string[] args)
{
SingletonClass s1 = SingletonClass.Instance();
SingletonClass s2 = SingletonClass.Instance();
if (s1 == s2)
{
Console.WriteLine("Same Object");
}
else
{
Console.WriteLine("Different Object");
}
s1.strName = "Vinoth";
s2.strName = "Harshad";
Console.WriteLine("s1: {0}, s2: {1}",s1.strName,s2.strName);
}
}
------------------------------------------------------------------------------------
OR
public
class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}