Singleton mode of design mode in 23

Java technology debt 2022-06-24 07:28:26 阅读数:592


Java Technical debt


In some systems , In order to save memory resources 、 Ensure the consistency of data content , Only one instance can be created for some classes , This is known as the singleton pattern .

The definition and characteristics of singleton pattern

Single case (Singleton) Definition of pattern : A class has only one instance , And this class can create a pattern of this instance by itself . for example ,Windows Only one task manager can be opened in , This can avoid the waste of memory resources caused by opening multiple task manager windows , Or there are errors such as inconsistent display contents of each window .

In computer system , also Windows The recycle bin 、 File system in operating system 、 Thread pool in multithreading 、 Graphics card driver object 、 Background processing services for printers 、 The log object of the application 、 Connection pool for database 、 Counters for websites 、Web Applied configuration objects 、 Dialog boxes in the application 、 The cache in the system is often designed as a single example .

Singleton mode is also widely used in real life , For example, the company CEO、 Department managers, etc. are all singleton models .J2EE Standard ServletContext and ServletContextConfig、Spring Framework application ApplicationContext、 The connection pool in the database is also singleton mode .

The singleton pattern is as follows 3 Characteristics :

  1. A singleton class has only one instance object ;
  2. The singleton object must be created by the singleton class itself ;
  3. The singleton class provides a global access point to access the singleton .

The advantages and disadvantages of the singleton pattern

Advantages of singleton mode :

  • The singleton mode ensures that there is only one instance in memory , Reduced memory overhead .
  • It can avoid multiple occupation of resources .
  • Singleton mode sets global access points , Can optimize and share access to resources .

Disadvantages of singleton mode :

  • Singleton mode generally has no interface , Extend the difficult . If you want to expand , In addition to modifying the original code , There is no second way , Against the principle of opening and closing .
  • In concurrent testing , Singleton mode is not good for code debugging . In the course of debugging , If the code in the singleton is not finished , You can't simulate a new object .
  • The function code of singleton pattern is usually written in a class , If the function design is unreasonable , It is easy to violate the principle of single responsibility .

The singleton pattern looks very simple , It's also very simple to implement . Single case mode is a high-frequency interview question in the interview . I hope you can study hard , Master singleton mode , Enhance the core competitiveness , Add points to the interview , Got it Offer.

Application scenario of singleton mode

about Java Come on , Singleton mode can be guaranteed in a JVM There is only a single instance of . The application scenarios of singleton mode mainly include the following aspects .

  • Some classes that need to be created frequently , Using singletons can reduce the memory pressure of the system , Reduce GC.
  • When a class only needs to generate one object , Like a monitor in a class 、 Everyone's ID number, etc .
  • Some classes occupy more resources when creating instances , Or instantiation takes a long time , And often use .
  • A class needs to be instantiated frequently , When the created objects are destroyed frequently , Such as multithreaded thread pool 、 Network connection pool, etc .
  • Objects that frequently access databases or files .
  • For some control hardware level operations , Or from the system point of view, it should be a single control logic operation , If there are multiple instances , Then the system will be completely out of order .
  • When objects need to be shared . Because singleton mode allows only one object to be created , Sharing this object saves memory , And speed up object access . Such as Web Configuration object in 、 Database connection pool, etc .

The structure and implementation of singleton pattern

Singleton pattern is one of the simplest patterns in design pattern . Usually , The constructor of a normal class is public , External classes can pass through “new Constructors ()” To generate multiple instances . however , If the constructor of the class is set to private , The constructor cannot be called by an external class , It is impossible to generate multiple instances . At this point, the class itself must define a static private instance , And provide a static public function to create or get the static private instance .

1. The structure of singleton pattern

The main roles of the singleton pattern are as follows .

  • Singleton class : A class that contains an instance and can create it by itself .
  • Access class : Classes that use singletons .

Java Technical debt

2. Implementation of the singleton pattern

The singleton pattern usually has two implementations .

  1. An example of lazy style

The feature of this pattern is that no singleton is generated when the class is loaded , Only when the first call getlnstance Method to create the singleton . The code is as follows :

public class LazySingleton {

private static volatile LazySingleton instance = null; // Guarantee instance Synchronize across all threads 
private LazySingleton() {

} //private Avoid classes being instantiated externally 
public static synchronized LazySingleton getInstance() {

//getInstance Methods are preceded by synchronization 
if (instance == null) {

instance = new LazySingleton();
return instance;

Be careful : If you write a multithreaded program , Do not delete the keyword in the above example code volatile and synchronized, Otherwise, there will be the problem of thread insecurity . If you don't delete these two keywords, you can guarantee thread safety , But synchronize every time you visit , Will affect performance , And consume more resources , This is the disadvantage of lazy singleton .

  1. Hungry han singleton

The feature of this pattern is that once a class is loaded, a singleton is created , Make sure to call getInstance The single example before the method already exists .

public class HungrySingleton {

private static final HungrySingleton instance = new HungrySingleton();
private HungrySingleton() {

public static HungrySingleton getInstance() {

return instance;

While creating a class, a static object has been created for the system to use , No more changes in the future , So it's thread safe , Can be used directly for multithreading without problems .

There is also a lock mode : Double lock mode

// The double lock mode of the full Han mode , Increase of efficiency 
public class Singleton3 {

private static Singleton3 singleton;
private Singleton3(){

public static Singleton3 getInstance(){

if(singleton == null){


if(singleton == null){

singleton = new Singleton3();
return singleton;

Comparison of several models :

1、 The hungry man model is Thread safe , Because the instance object will be created during class loading , stay getInstance() Method simply returns the object reference directly . It's called “ The hungry ”, Because this mode creates instance object comparison “ emergency ”, I am really hungry ……

** benefits :** Simple and clear , No thread safety concerns .

shortcoming : If you use too many hungry men in a large environment , Will produce too many instance objects , Whether you want to use them or not .

2、 Satiety mode Not thread safe , Because instance objects are generated only when necessary , Before production, we will judge whether the object reference is empty , here , If multiple threads enter the judgment at the same time , Multiple instance objects will be generated , This is not consistent with the idea of singleton . So fullness mode is to ensure thread safety , Just use synchronized The keyword identifies the method . It's called “ Satiate a man ”, Because it's full , Don't rush to produce instances , It will be produced when necessary .

benefits : Delay loading , The object will be produced only when it is used .

shortcoming : Need to be synchronized , Pay the price of efficiency .

3、 Double lock mode , It is the optimization of the mode of satiating the Han people , Make a double judgment , When the instance object has been created, there is no need to lock it , Increase of efficiency . It is also a recommended way .

Application examples of singleton mode

such as : Using the lazy singleton model to simulate the current president of the United States .

analysis : In every term , There is only one president of the United States , So this example is suitable to be implemented in singleton mode , chart 2 Shown is the structure diagram of lazy singleton implementation .

Java Technical debt

chart 2 Structure diagram of U.S. President generator

The program code is as follows :

public class SingletonLazy {

public static void main(String[] args) {

President zt1 = President.getInstance();
zt1.getName(); // Output the president's name 
President zt2 = President.getInstance();
zt2.getName(); // Output the president's name 
if (zt1 == zt2) {

System.out.println(" They are the same person !");
} else {

System.out.println(" They are not the same person !");
class President {

private static volatile President instance = null; // Guarantee instance Synchronize across all threads 
//private Avoid classes being instantiated externally 
private President() {

System.out.println(" Produce a president !");
public static synchronized President getInstance() {

// stay getInstance Method plus synchronization 
if (instance == null) {

instance = new President();
} else {

System.out.println(" There is already a president , Can't produce a new president !");
return instance;
public void getName() {

System.out.println(" I am the president of the United States : trump .");

The program runs as follows :

 Produce a president !
I am the president of the United States : trump .
There is already a president , Can't produce a new president !
I am the president of the United States : trump .
They are the same person !

The expansion of singleton mode

The singleton pattern can be extended to a limited number of instances (Multitcm) Pattern , This pattern can generate a limited number of instances and store them in ArrayList in , It can be obtained at random when customers need it , Its structure is shown in the figure 5 Shown .

Java Technical debt

More please move ...

The author of this article :Java Technical debt
Link to the original text :
Copyright notice : All articles in this blog except special statement , All adopt CC BY 3.0 CN License by agreement . For reprint, please sign the author and indicate the source of the article .

copyright:author[Java technology debt],Please bring the original link to reprint, thank you.