The basic definition

The singleton pattern ensures that there is only one instance of a class and provides a global access point. The singleton pattern has the following characteristics:

It has only one instance.

It must instantiate itself.

It must provide its own access points to the entire system.

Code implementation

The hungry type

Initialize static variables directly. This ensures thread safety.

LanHanShi

Load on demand. Synchronized. That is, make the getInstance() method synchronous

advantages

System resources are saved. Since there is only one instance object in the system, the singleton pattern undoubtedly saves system resources and improves system performance for some systems that need to create and destroy objects frequently.

Because a singleton class encapsulates its unique instance, it has tight control over how and when customers access it.

disadvantages

Because there is no layer of abstraction in the singleton pattern, it is difficult to extend the singleton class.

The JDK source

LanHanShi

java.lang.Runtim


The hungry type

java.lang.System

​​​​​​​