The singleton pattern can be said to be one of the most commonly used design patterns. Its main function is to ensure that a class has only one instance and provide a global access point to access it, with strict control. User's access method.
The singleton mode is divided into the lazy mode and the hungry mode. First let’s talk about the hungry mode:
The hungry mode
The hungry mode It's a bit like being hungry, like a person who has been hungry for a long time, so he will eat as long as someone gives him something, regardless of whether the food tastes good or whether he can eat it. The code is as follows:
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
Everyone knows the meaning. It is a static initialization method. The object is instantiated as soon as the class is loaded. The advantage is thread safety, but the disadvantage is that it occupies system resources in advance. At this time, the lazy mode appears:
(Recommended video: java video tutorial)
lazy mode
Compared with the hungry man mode, which is not selective about food, the lazy man mode means eating only when the food is brought to your mouth, otherwise you will not move your mouth no matter how hungry you are. The code is as follows:
public class Singleton{ private static Singleton instance; private Singleton(){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
However, when multiple threads call the getInstance() method at the same time, it is possible to create multiple instances, so this version of the thread is unsafe, so the following version is created:
public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton .class) { if (instance == null) { instance = new Singleton (); } } } return instance; } }
Use double locking method to ensure that when instance == null, multiple threads can pass the first level of judgment when calling the getInstance() method.
Under normal circumstances, Hungry Han’s singleton mode can meet most needs. This is the basic situation about the singleton mode.
This article comes from php Chinese website, java tutorial column, welcome to learn!
The above is the detailed content of Code explains java's singleton pattern. For more information, please follow other related articles on the PHP Chinese website!