Singleton Design Pattern

Singleton design pattern allows to create only one instance of the class by providing only one global point to access it.
This can be achieved by:

    1. Making the constructor private/protected.
    2. Create a static function which returns an instance of the class only after ensuring class has no other instance.


namespace OopConcept
{
///
/// Class without explicit contructor
///

class singleton
{
private static singleton singletonInstance = null;

///
/// To prevent instantiation.
///

private singleton()
{

}
public static singleton getInstance()
{
if (singletonInstance == null)
{
singletonInstance = new singleton();
}
return singletonInstance;
}

}
///
/// Main Class -
///

class MainClass
{
public static void Main()
{
// Cannot create an instance with 'new' Keyword.
singleton firstInstance = singleton.getInstance();
singleton secondInstance = singleton.getInstance();

if (firstInstance == secondInstance)
{
Console.WriteLine("Two instances are same");
Console.Read();
}
}
}
}

0 comments:

Post a Comment