Instructions for use
1. Initialize the singleton when the class is loaded and return it directly when accessing in the future.
Advantages and Disadvantages
2. The advantage is that it is inherently thread-safe (thanks to the class loading mechanism) and there is no delay when using it. The disadvantage is that it may cause a waste of resources (if the singleton is not used after the class is loaded).
Example
public class HelloWorld { //创建私有静态的本类对象 private static HelloWorld hello = new HelloWorld(); //私有化构造函数 private HelloWorld(){}; //定义公有并静态的方法,返回该对象。 public static HelloWorld hello() { return hello; } }
The above is the detailed content of How to use hungry pattern in java singleton. For more information, please follow other related articles on the PHP Chinese website!