This article shares the specific code of the singleton pattern of Java design pattern for your reference. The specific content is as follows
concept:
Singleton pattern: There is only one instance in a class.
A class has and only one instance and provides a global access point.
Causes of using this mode:
When we are browsing websites, some websites will display "current number of people online". Generally, the way to implement this function is to store each logged in IP in a memory, file or database, and each additional IP is achieved "+1". Generally, it is a method, such as add(), to realize the function of "+1". For example, use the "update" statement to obtain the data stored in the database first, then +1, update the data in the database, and then save it; when displayed on the page, you can obtain the data in the database through another method. However, when multiple users log in at the same time, if each of them needs to new an object, then execute the add() method through the "Object. Method Name" call, and then store the data in the database, this will cause multiple users to be unable to accurately record the actual user data into the database. Therefore, designing this counter as a global object (everyone uses this object, instead of one, new one), and everyone shares the same data, can avoid similar problems. This is one of the applications of the singleton pattern we call.
Similarly, in other scenarios, similar scenarios will be encountered and similar ideas will be used. for example:
1. External resources: Each computer has several printers, but only one PrinterSpooler can be used to avoid two print jobs being output to the printer at the same time. Internal resources: Most software has one (or more) attribute files to store system configurations. Such a system should have an object to manage these attribute files. 2. Windows' Task Manager (task manager) is a typical singleton mode (this is very familiar). Think about it, can you open two windows task managers? If you don't believe it, try it yourself~
3. Recycle Bin for windows is also a typical singleton application. During the entire system operation, the recycling bin has maintained only one instance.
4. The counter of the website is generally implemented in singleton mode, otherwise it will be difficult to synchronize.
5. How can the application log application be implemented in singleton mode? This is generally because the shared log file is always open, because there can only be one instance to operate, otherwise the content will be difficult to add.
6. The singleton mode is generally used for reading configuration objects in web applications, because the configuration file is a shared resource.
7. The design of database connection pools generally adopts a singleton mode, because database connection is a database resource. The use of database connection pools in database software systems mainly saves efficiency losses caused by opening or closing database connections. This efficiency loss is still very expensive, because the singleton mode can greatly reduce this loss.
8. The design of multi-threaded thread pools generally adopts singleton mode, because the thread pool needs to facilitate control of threads in the pool.
9. The file system of the operating system is also a specific example of the implementation of large singleton mode. An operating system can only have one file system.
10. HttpApplication is also a typical application of unit examples. Anyone familiar with the entire request life cycle of ASP.Net (IIS) should know that HttpApplication is also a singleton pattern, and all HttpModules share an HttpApplication instance.
To sum up, the general application scenarios of singleton mode are:
1. Objects that need to be instantiated frequently and then destroyed.
2. Objects that take too much time or too much resource when creating objects, but are often used.
3. Stateful tool-like objects.
4. Frequent access to database or file objects.
5. In the case of resource sharing, avoid performance or loss caused by resource operation. Such as the log files, application configurations, etc. in the above.
6. When controlling resources, facilitate mutual communication between resources. Such as thread pools, etc.
Features:
1. There can only be one instance in a singleton class;
2. The singleton class must create its own unique instance;
3. The singleton class must provide this instance to all other objects.
Singleton pattern elements:
1. Private construction method
2. Private static reference points to your own instance
3. Public static method with its own instance as the return value
There are three ways to implement singleton pattern:
1. Hungry style: Singleton instances are built when class loading and are urgently initialized. (Preload method)
/*** Hungry Man Style (recommended)**/public class Test { private Test() { } public static Test instance = new Test(); public Test getInstance() { return instance; }} advantage
1. Thread safety
2. A static object has been created while the class is loading, and the response speed is fast when calling it
shortcoming
Resource efficiency is not high, and getInstance() may never be executed, but if other static methods of the class are executed or the class (class.forName) is loaded, then this instance is still initialized.
2. Lazy style: Singleton instances are built when used for the first time and are initialized.
class Test { private Test() { } public static Test instance = null; public static Test getInstance() { if (instance == null) { //When multiple threads determine that the instance is null, multiple threads will have duplication when performing new operations instance = new Singleton2(); } return instance; }} advantage
Avoid the creation of cases without using them in the form of hungry men. The resource utilization rate is high. If you do not execute getInstance(), you will not be instanced. Other static methods of this class can be executed.
shortcoming
There is no problem with lazy style in a single thread, but when colleagues access multiple threads, they may create multiple instances, and these multiple instances are not the same object. Although the instances created later will overwrite the instances created first, there will still be cases where different objects are obtained. The solution to this problem is to lock synchonized, which is not fast enough when loading for the first time, and the unnecessary synchronization overhead of multi-threading is high.
3. Double detection
class Test { private Test() { } public static Test instance = null; public static Test getInstance() { if (instance == null) { synchronized (Test.class) { if (instance == null) { instance = new Test(); } } return instance; }} advantage
The resource utilization rate is high. If you do not execute getInstance(), you will not be instanced. You can execute other static methods of this class.
shortcoming
The response was not fast when loading for the first time, and occasionally failed due to some reasons of the java memory model.
4. Static internal classes
class Test { private Test() { } private static class SingletonHelp { static Test instance = new Test(); } public static Test getInstance() { return SingletonHelp.instance; }} advantage
The resource utilization rate is high, and it is not executed without getting the instance. You can execute other static methods of this class.
shortcoming
Not fast enough when loading for the first time
Summarize:
Generally, hungry style is used. If you care very much about resources, you can use static internal types. It is not recommended to use lazy style and double detection.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.