Singleton Pattern


The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.
 
Example1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class SingletonFlight {
 public static void main(String[] bag){
  SingleTon singleTon = SingleTon.getInstance(); 
  System.out.println(singleTon.getInfo());
 }
}
==========
public class SingleTon {
 private static SingleTon instance = new SingleTon();
 
 public static SingleTon getInstance(){
  return instance;
 }
 
 public String getInfo(){
  return "I am SingleTon object";
 }
}
==========
Example2
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static synchronized Singleton getInstance() {
     if (uniqueInstance == null) {
        uniqueInstance = new Singleton();
     }
     return uniqueInstance;
}
// other useful methods here
}
==========
Example3
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
       synchronized (Singleton.class) {
         if (uniqueInstance == null) {
           uniqueInstance = new Singleton();
         }
      }
}
return uniqueInstance;
}
}