Singleton Pattern is used to control the instantiation of a class. A Singleton class can have only one instance and the class provides a global access point to that instance. The singleton class has the following responsibility:
- ensures that only one instance of the class is created.
- provides access to that instance of the object.
- ideally the singleton instance should be created only when it is needed.
There are situation when we need a single unique instance of a class. To do this we can make the constructor of the class private so that only the class itself is capable of creating an instance of itself. We can hold the instance of the singleton class in a global variable and provide access to this instance through a global method. However, a global variable would exist for the duration of the program taking up resources. This could become a problem when the instance is resource-intensive. Therefore, you may want to create such an object only when it is needed.
Singleton
|
private
static Singleton singleton
|
public
static Singleton getSingleton()
|
public class Singleton
{
private static Singleton singleton;
private static Singleton singleton;
private Singleton() { }
public static Singleton getSingleton()
{
if (singleton == null)
if (singleton == null)
singleton = new Singleton();
return singleton;
}
}
}
}
Bibliography
Bishop, J. (2016, 12 30). Creational Patterns: Prototype, Factory Method, and Singleton. Retrieved from MSDN: https://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx
Comments
Post a Comment