The purpose of the singleton pattern is to ensure that only one instance of a class is created and provides a way to access that instance. This pattern is useful when you are dealing with resource-intensive objects, or when the same object instance is to be passed and used in multiple places.
Let's see a general example:
You can see the class declares a static variable instance whose visibility is private. This way the instance can't be accessed directly by the external world. The constructor of the class is private meaning that you can't instantiate the Singleton class using the new keyword. However, you can still instantiate it from within the class. The method getInstance() is a public and static method that returns the instance to the caller and it's an access point to the instance. Its job is to instantiate Singleton if an instance doesn't exist.
Let's see some code:
public class Singleton {
static private Singleton singleton = null;
private Singleton() {}
static public Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
public void print(){
System.out.println("Singleton already instanciated");
}
}
This implementation is characterized in that a single instance is created when it's first used. You can see that the constructor is private to avoid creating other instances and the method getInstance() is in charge of evaluating if an instance is already created.
Joshi, B. (2016b). Beginning SOLID Principles and Design Patterns for ASP.NET Developers (English Edition) (1st ed.). Apress.
Comments
Post a Comment