Hungry man mode of singleton mode

The lazy mode mentioned above is clicked to open the link , and then the hungry mode is introduced.

What is Hungry Man Mode?

Hungry mode: When this class is loaded, the object will be created immediately. Hungry mode is faster to get objects at runtime and slower to load classes.

Code:

class Singleton {
	//Create its own object inside the singleton class
	private static final Singleton s=new Singleton();
	//private the constructor
	private Singleton() {}
	public static Singleton getSingleton() {
		return s;
	}
	//test
	public static void main(String[] args) {

		// only one object
		Singleton s1=Singleton.getSingleton();
		System.out.println(s1);
		
		Singleton s2=Singleton.getSingleton();
		System.out.println(s2);
	}

}

In general, the two modes have their own characteristics, but most of them use the Hungry Man mode, which is simple and safe.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324749819&siteId=291194637