1public class SingletonClass {
2 private static final SingletonClass SINGLE_INSTANCE = new SingletonClass();
3 private SingletonClass() {}
4 public static SingletonClass getInstance() {
5 return SINGLE_INSTANCE;
6 }
7}
1- A private constructor
2- A static field containing its only instance
3- A static factory method for obtaining the instance
4
5public final class ClassSingleton
6{
7
8 private static ClassSingleton INSTANCE;
9 private String info = "Initial info class";
10
11 private ClassSingleton()
12 {
13 }
14
15 public static ClassSingleton getInstance()
16 {
17 if(INSTANCE == null)
18 {
19 INSTANCE = new ClassSingleton();
20 }
21
22 return INSTANCE;
23 }
24
25 // getters and setters
26}
27
28 =============Usage============
29
30
31To use our ClassSingleton, we simply need to get the instance statically:
32
33ClassSingleton classSingleton1 = ClassSingleton.getInstance();
34
35System.out.println(classSingleton1.getInfo()); //Initial class info
36
37ClassSingleton classSingleton2 = ClassSingleton.getInstance();
38classSingleton2.setInfo("New class info");
39
40System.out.println(classSingleton1.getInfo()); //New class info
41System.out.println(classSingleton2.getInfo()); //New class info
42
1public class SingletonOnDemand {
2
3 private SingletonOnDemand () {}
4 private static class Singleton {
5 private static final SingletonOnDemand instance = new SingletonOnDemand();
6 }
7
8 public static SingletonOnDemand getInstance () {
9 System.out.println("create instance");
10 return Singleton.instance;
11 }
12}
1public final class SomeSingleton {
2 public static final SomeSingleton INSTANCE;
3
4 private SomeSingleton() {
5 INSTANCE = (SomeSingleton)this;
6 System.out.println("init complete");
7 }
8
9 static {
10 new SomeSingleton();
11 }
12}
1public final class ClassSingleton {
2
3 private static ClassSingleton INSTANCE;
4 private String info = "Initial info class";
5
6 private ClassSingleton() {
7 }
8
9 public static ClassSingleton getInstance() {
10 if(INSTANCE == null) {
11 INSTANCE = new ClassSingleton();
12 }
13
14 return INSTANCE;
15 }
16
17 // getters and setters
18}