The code copy is as follows:
package net.kitbox.util;
/**
*
* @author lldy
*
*/
public class Singleton {
private Singleton(){
}
private static class SingletonHolder{
private static Singleton instance = new Singleton();
}
public static void method(){
SingletonHolder.instance._method();
}
private void _method(){
System.out.println("Singleton Method!");
}
public static void main(String[] args) {
Singleton.method();
}
}
This writing takes advantage of the loading principle of the class loader, each class will only be loaded once, so that a singleton object is generated when its internal static class is loaded, and this process is thread-safe.
The method() method encapsulates the private method of the internal singleton object and is used as an external interface, so it can be called as follows
The code copy is as follows:
Singleton.method();
//It is easier to use frequently than the common Singleton.getInstance().method()
Another way is to use enumerations to implement.
The above is all about this article, I hope you like it.