The main reason is to avoid creating objects repeatedly

There are roughly synchronized lazy, double check, static internal class, enumeration five implementation methods

The hungry type:

public class Test1 { private final static Test1 test1 = new Test1(); private Test1(){ } public static Test1 getInstance(){ return test1; }}Copy the code

Synchronized:

public class Test2 { private static Test2 test2; private Test2(){ } public synchronized static Test2 getInstance(){ if(test2 == null){ test2 = new Test2(); } return test2; }}Copy the code

Double check:

public class Test3 { private static volatile Test3 test3; private Test3(){ } public static Test3 getInstance(){ if(test3 == null){ synchronized (Test3.class){ if(test3 == null){ test3 = new Test3(); } } } return test3; }}Copy the code

Static inner class:

public class Test4 { private Test4(){ } private static class Holder{ private static final Test4 test4 = new Test4(); } public static Test4 getInstance(){ return Holder.test4; }}Copy the code

Enumeration:

public enum  Test5 {
    INSTANCE;
}
Copy the code