18
loading...
This website collects cookies to deliver better user experience
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance
.Stated here, A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital
.
Ok now putting the copy pasta and technical definitions aside. We can conclude that to use a singleton pattern means that we only want to create one instance of our class. How can we do that? Well the answer lies in the static
keyword and using a private constructor. However, before I can explain more I must establish that you and I have the same level of understanding when it comes to what the static
keyword means.
static
comes into play.class variable
or a static variable
. Theses class variables are commonly used when we want to share a variable across all instances. I should also point out that our class variable private static Singleton uniqueInstance;
is static for another reason but more on that later.Static methods look like normal methods but they have the static keyword in their declarations. A static method should be invoked by using the class name. So to invoke our static method we would do this, Singleton.getInstance()
. Another important thing to note is that static methods can only access other static method/variables, you can NOT access instance method/variables from a static method. You also can not use the this
keyword inside of a static method.
Now that we both have a basic understanding of how the static
keyword works we can move forward.
Singleton.getInstance()
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
As you can see we have our private constructor, the uniqueInstance == null
will guarantee that we only have one instance of the class. The new instance is assigned to the private static Singleton uniqueInstance;
variable. If you are wondering why it is static, it is because we created the new instance inside of a static method and static methods only have access to static variables. So the static method and variable are all necessary because we have a private constructor.
This is just the basics of the singleton pattern and design patterns in general, so I encourage you to read more about them.