Can you explain singleton pattern?

There are situations in project where we want only one instance of the object to be created and shared between the clients. For instance let’s say we have the below two classes, currency and country.
These classes load master data which will be referred again and again in project. We would like to share a single instance of the class to get performance benefit by not hitting the database again and again.

public class Currency
{
List<string> oCurrencies = new List<string>();
public Currency()
{
oCurrencies.Add("INR");
oCurrencies.Add("USD");
oCurrencies.Add("NEP");
oCurrencies.Add("GBP");
}
public IEnumerable<string> getCurrencies()
{
return (IEnumerable<string>)oCurrencies;
}
}
public class Country
{
List<string> oCountries = new List<string>();
public Country()
{
oCountries.Add("India");
oCountries.Add("Nepal");
oCountries.Add("USA");
oCountries.Add("UK");
}
public IEnumerable<string> getCounties()
{
return (IEnumerable<string>) oCountries;
}
}

Implementing singleton pattern is a 4 step process.
Step 1: Create a sealed class with a private constructor
The private constructor is important so that clients cannot create object of the class directly. If you remember the punch, the main intention of this pattern is to create a single instance of the object which can be shared globally, so we do not want to give client the control to create instances directly.

public sealed class GlobalSingleton
{
private GlobalSingleton() { }
………..
……….
}

Step 2: Create aggregated objects of the classes (for this example it is currency and country) for which we want single instance.

public sealed class GlobalSingleton
{
// object which needs to be shared globally
public Currency Currencies = new Currency();
public Country Countries = new Country();

Step 3: Create a static read-only object of t he class itself and expose the same via static property as shown below.

public sealed class GlobalSingleton
{
….
…
// use static variable to create a single instance of the object
static readonly GlobalSingleton INSTANCE = new GlobalSingleton();
public static GlobalSingleton Instance
{
get
{
return INSTANCE;
}
}
}

Step 4: You can now consume the singleton object using the below code from the client.

GlobalSingleton oSingle = GlobalSingleton.Instance;
Country o = osingl1.Country;

Below goes the complete code for singleton pattern which we discussed above in pieces.

public sealed class GlobalSingleton
{
// object which needs to be shared globally
public Currency Currencies = new Currency();
public Country Countries = new Country();
// use static variable to create a single instance of the object
static readonly GlobalSingleton INSTANCE = new GlobalSingleton();
/// This is a private constructor, meaning no outsides have access.
private GlobalSingleton()
{ }
public static GlobalSingleton Instance
{
get
{
return INSTANCE;
}
}
}
Tagged , , . Bookmark the permalink.

Leave a Reply