JAVA Static method and Singleton Mode
Recently, when I used sonar to evaluate the code quality, I found a problem. Some util classes in the project, the static methods previously written, all prompted that it is best to use the singleton Method for correction.
For this reason, I thought carefully and found that it still makes sense. Here I will talk about my personal understanding of the static method and Singleton mode.
I will not explain the singleton mode too much. I recommend the Zen book of java design patterns for a better understanding.
Here I will talk about two methods:
In the past, I used to write some public classes without thinking about them as follows:
Public class DateUtil {
Public final static String DATEFORMAT = "YYYY-MM-DD ";
Private DateUtil (){
}
Public static void changeDateFormat (){
}
} |
Directly call DateUtil. changeDateFormat ();
If you want this class to be used as a Singleton, OK, you can directly add a private constructor to the method.
In this way, you can avoid a new object and call methods, which seems good.
In fact, the biggest drawback of this method is that static is used as a static method, and is loaded into the memory when loading classes. No matter whether you use it or not, it occupies this position, this design is not recommended.
This problem is well solved using the singleton mode:
Public class DateUtil {
Public final String DATEFORMAT = "YYYY-MM-DD ";
Public static DateUtil instance = null;
Private DateUtil (){
}
Private static Integer LOCK = 0;
Public static DateUtil getInstance (){
Synchronized (LOCK ){
If (instance = null ){
Instance = new DateUtil ();
}
Return instance;
}
}
Public void changeDateFormat (){
}
} |
Similarly, this method ensures that the user can only obtain one instance, in line with the design philosophy of a single instance.
At the same time, the method is added to the memory only when the method is called using this instance. When the object is not used, gc recycles the method, which is much more efficient, of course, the singleton I constructed here is thread-safe.
Here is a brief introduction. If you are interested in JAVA memory, you can read my previous articles. Here we also recommend another brother. The link is sent:
1. http://blog.csdn.net/hongshan50/article/details/40583875
2. If you are interested in using JAVA memory for static and common methods, read the following article:
Http://blog.sina.com.cn/s/blog_4fe01e630100g775.html