The singleton pattern is a specific design pattern that I have heard since I knew the noun of the design pattern. Its usage scenario is that there are some key resources that allow only one instance to be generated. If more than one instance is generated, there will be a lot of disruption to our reality.
Here are a few points I've summed up in the course of reading:
- Ensure that a class has only one instance and provides a global access instance.
- Implementing a singleton pattern in Java requires a private construction method, a static method, and a static instance.
- Identify limitations on performance and resources, and then carefully select the appropriate scenario to implement the singleton to solve the multithreading problem (we must assume that all programs are multithreaded)
- If more than one class loader is used, it may result in a single failure, resulting in multiple instances
- There are two types of singleton patterns: Lazy mode and a hungry man mode
- Lazy Mode: Loads the class faster, but the runtime gets the object at a slower speed because there is no object created for the class when the Singleton class is created. Thread is unsafe. To add the Syncronized keyword to the getinstance () method, if you need to add a double lock for efficiency
- A hungry man mode: Loading classes is slow, but it is faster to get objects at run time. Because the object of the class was created when the Singleton class was created. is thread-safe.
The code of the singleton pattern itself is very small, but the amount of code does not mean it is very simple, to understand its true thinking, but also to use more thinking.
"Design pattern" Java Design Pattern the second lesson of the singleton mode