class
Singleton Object example
With this example we are going to demonstrate how to create and use a Singleton class. The Singleton’s purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. In short, to create and use a Singleton class we have followed the steps below:
- We have created a class,
MySingleton
that has astatic MySingleton
field. It has a private constructor, to prevent other classes from instantiating. - It has a static method,
MySingleton
createMySingleton()
, that checks theMySingleton
field, and if it is null it creates a new one and finally returns it. - We create two new instances calling
createMySingleton()
method ofMySingleton
and check if they are equal, returning true if they are. - Both objects created are fields of the same object, so they are equal.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; class MySingleton { // the static singleton object private static MySingleton theObject; private MySingleton() { } public static MySingleton createMySingleton() { if (theObject == null) theObject = new MySingleton(); return theObject; } } public class Singleton { public static void main(String[] args) { MySingleton ms1 = MySingleton.createMySingleton(); MySingleton ms2 = MySingleton.createMySingleton(); System.out.println(ms1 == ms2); } }
Output:
true
This was an example of how to create and use a Singleton class in Java.