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}