Design Patterns - Singleton Pattern
Singleton pattern ensures that only one instance of a class is created. It provides a global access point o that object. We will show how to achieve Singleton pattern with an example and where we can use it frequently.
Singleton pattern ensures that only one instance of a class is created. It provides a global access point o that object. We will show how to achieve Singleton pattern with an example and where we can use it frequently.Singleton Pattern
Singleton pattern ensures that only one instance of a class is created. It provides a global access point of that object. This approach is referred to as lazy instantiation. Lazy instantiation avoids instantiating unnecessary instance when an applications starts.
ParticipantsStatic Member
The static member holds the object of the same class itself. This object will be instantiated inside the Static property.Private Constructor
Private constructor will not allow other classes to create instance of this class. The private modifier is usually used explicitly to make it clear that the class cannot be instantiatedStatic Property
This property holds the instance of the class. The class gets instantiated only when an object asks for an instance. It will create an instance only if the instance is not null. Example
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}Applicability Example
Drawbacks
Singleton approach is not safe for multi threaded environments. If different threads entered the instance property at the same time, more than one instance of the singleton class may be created.