#
Singleton
This tutorial explains to you the design pattern named Singleton (which is a Creational Pattern).
#
Singleton Pattern - theory
A Singleton
, is a class which is instantiated once per application and exist for the lifecycle of the application.
A Singleton Design Pattern is a pattern for creating a singleton object. The pattern is used when you need an object to be instantiated per application and per container.
#
Singleton Pattern - example
Here it is the UML Diagram for Singleton Pattern (Example):
When we create a singleton, we have to take care of the following:
- the constructor must be private: the object cannot be created outside the class.
- we will not create another object, but only the instance of the first object (created when the class is used for the first time for - see the
static
keyword in the code below).
Here is the code for creating a singleton object (my example) and the code for testing it :
public class SingletonClass {
private int instanceNumber;
//create an object of SingletonClass when the class is used for the first time
private static SingletonClass instance = new SingletonClass();
//the constructor is private so that this class cannot be instantiated
private SingletonClass(){
instanceNumber = instanceNumber + 1;
}
//Get the only object available
public static SingletonClass getInstance(){
return instance;
}
//Test if there are more then 1 instances
public void getInstanceNumber(){
System.out.println("This is instance #"+instanceNumber+" !");
}
}
public class SingletonUsageExample {
public static void main(String[] args) {
SingletonClass object1 = SingletonClass.getInstance();
object1.getInstanceNumber();
SingletonClass object2 = SingletonClass.getInstance();
object2.getInstanceNumber();
}
}
And here you have the example result :