Static inner class implementation of singleton mode
Directly upload the code, everyone who understands it can understand it, and those who don’t understand it should read:
package singleton;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class InnerSingletonTest {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Constructor declaredconstructor=InnerSingleon.class.getDeclaredConstructor();
declaredconstructor.setAccessible(true);
InnerSingleon instance2=declaredconstructor.newInstance();
InnerSingleon instance1=InnerSingleon.getInstance();
System.out.println(instance1==instance2);
}
}
class InnerSingleon{
private static class InnerSingletonHolder{
private static InnerSingleon instance=new InnerSingleon();
}
//防止反射创建多个实例
private InnerSingleon(){ if(InnerSingletonHolder.instance!=null){ throw new RuntimeException("Singleton does not allow multiple instances"); } };
public static InnerSingleon getInstance(){
return InnerSingletonHolder.instance;
}
}
Result:
Exception in thread “main” java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect .DelegatingConstructorAccessorImpl.newInstance (DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at singleton.InnerSingletonTest.main(InnerSingletonTest.java:10)
Caused by: java.lang.RuntimeException: Singleton not allowed Multiple instances
Another implementation of the singleton pattern.
The singleton enum implementation method will not be repeated here. A singleton implemented with an enumeration type cannot be destroyed by reflection, clone, or deserialization. If you don't believe me, give it a try.