java design pattern - singleton pattern

java design pattern - singleton pattern

preface

Singleton Pattern is one of the simplest design patterns in Java. This type of design pattern is a creation pattern, which provides the best way to create objects.
This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique object, which can be accessed directly without instantiating the object of this class.

1, What is singleton mode?

Singleton Pattern is one of the simplest design patterns in Java. This type of design pattern is a creation pattern, which provides the best way to create objects.

be careful:

1. A singleton class can only have one instance.
2. A singleton class must create its own unique instance.
3. A singleton class must provide this instance to all other objects.

2, Definition and characteristics of singleton mode

Definition of Singleton mode:
A pattern in which a class has only one instance and the class can create the instance itself.
For example, only one task manager can be opened in Windows, which can avoid the waste of memory resources caused by opening multiple task manager Windows, or errors such as inconsistent display contents of each window.
In the computer system, there are also the recycle bin of Windows, the file system in the operating system, the thread pool in multithreading, the driver object of graphics card, the background processing service of printer, the log object of application program, the connection pool of database, the counter of website, the configuration object of Web application, the dialog box in application program The cache in the system is often designed as a singleton.

The singleton model is also widely used in real life. For example, the company CEO and department manager all belong to the singleton model. ServletContext and ServletContextConfig in J2EE standard, ApplicationContext in Spring framework application and connection pool in database are also singleton mode.

The singleton mode has three features:
A singleton class has only one instance object;
The singleton object must be created by the singleton class itself;
The singleton class provides a global access point for accessing the singleton.

3, Advantages and disadvantages of singleton mode

Advantages of singleton mode:
1. The singleton mode can ensure that there is only one instance in the memory and reduce the memory overhead.
2. Multiple occupation of resources can be avoided.
3. Set global access points in singleton mode to optimize and share resource access.

Disadvantages of singleton mode:
1. The singleton mode generally has no interface and is difficult to expand. If you want to expand, there is no second way except to modify the original code, which violates the opening and closing principle.
2. In concurrent testing, singleton mode is not conducive to code debugging. During debugging, if the code in the singleton is not executed, a new object cannot be simulated.
3. The function code of singleton mode is usually written in a class. If the function design is unreasonable, it is easy to violate the principle of single responsibility.

4, Structure and implementation of singleton mode

Singleton pattern is one of the simplest design patterns. Generally, the constructors of ordinary classes are public, and external classes can generate multiple instances through "new constructor()". However, if the constructor of a class is made private, the external class cannot call the constructor and cannot generate multiple instances. At this time, the class itself must define a static private instance and provide a static public function to create or obtain the static private instance.

The basic structure and implementation method are analyzed below.

1. Structure of singleton mode

The main roles of singleton mode are as follows.
1. Singleton class: a class that contains an instance and can create it by itself.
2. Access class: class using singleton.
Its structure is shown in Figure 1.

2. Implementation of singleton mode

There are usually two implementations of the Singleton pattern.
Type 1: lazy single case

The characteristic of this mode is that no singleton is generated when the class is loaded, only when it is called for the first time getlnstance Method to create this singleton. The code is as follows:
public class LazySingleton {
    private static volatile LazySingleton instance = null;    //Ensure that instance is synchronized in all threads
    private LazySingleton() {
    }    //private prevents classes from being instantiated externally
    public static synchronized LazySingleton getInstance() {
        //Add synchronization before getInstance method
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}
Note: if you are writing a multithreaded program, do not delete the keywords in the above example code volatile and synchronized,Otherwise, there will be thread unsafe problems. If you don't delete these two keywords, you can ensure thread safety, but you have to synchronize each access, which will affect performance and consume more resources. This is the disadvantage of lazy singleton.

Type 2: starving Han style single case

The feature of this pattern is that once the class is loaded, a singleton is created to ensure that the getInstance The singleton already exists before the method.
public class HungrySingleton {
    private static final HungrySingleton instance = new HungrySingleton();
    private HungrySingleton() {
    }
    public static HungrySingleton getInstance() {
        return instance;
    }
}
Hungry Chinese singleton has created a static object for the system to use at the same time of class creation, which will not be changed in the future. Therefore, it is thread safe and can be directly used for multithreading without problems.

5, Application examples of singleton mode

Example 1: the lazy singleton mode is used to simulate the generation of the current president object of the United States.
Analysis: in each term of office, there is only one president of the United States, so this example is suitable for single case mode.
Fig. 2 shows the structure diagram of a lazy single example.

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;    //Ensure that instance is synchronized in all threads
    //private prevents classes from being instantiated externally
    private President() {
        System.out.println("Produce a president!");
    }
    public static synchronized President getInstance() {
        //Add synchronization to getInstance method
        if (instance == null) {
            instance = new President();
        } else {
            System.out.println("There is already a president, can not produce a new president!");
        }
        return instance;
    }
    public void getName() {
        System.out.println("I am the president of the United States: trump.");
    }
}

The running results of the program are as follows:

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

Example 2: the hungry Han single case model is used to simulate the generation of pig Bajie objects.
Analysis: similar to the above example, there is only one pig Bajie, so this example is also suitable for single instance mode. Because this example wants to display the image of pig Bajie (click here to download the pig Bajie image to be displayed by the program), it uses the framework form JFrame component. The pig Bajie class here is a singleton class, which can be defined as a subclass of panel JPanel, which contains labels to save the image of pig Bajie. The customer form can obtain the pig Bajie object and display it.
Figure 3 shows the structure diagram of the implementation of starving Han style single example.

The program code is as follows:

import java.awt.*;
import javax.swing.*;
public class SingletonEager {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Hungry man single case mode test");
        jf.setLayout(new GridLayout(1, 2));
        Container contentPane = jf.getContentPane();
        Bajie obj1 = Bajie.getInstance();
        contentPane.add(obj1);
        Bajie obj2 = Bajie.getInstance();
        contentPane.add(obj2);
        if (obj1 == obj2) {
            System.out.println("They are the same person!");
        } else {
            System.out.println("They are not the same person!");
        }
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
class Bajie extends JPanel {
    private static Bajie instance = new Bajie();
    private Bajie() {
        JLabel l1 = new JLabel(new ImageIcon("src/Bajie.jpg"));
        this.add(l1);
    }
    public static Bajie getInstance() {
        return instance;
    }
}

The running results of the program are as follows:

They are the same person!

6, Application scenario of singleton mode

For Java, the singleton pattern ensures that there is only a single instance in a JVM. The application scenarios of singleton mode mainly include the following aspects.
1. For some classes that need to be created frequently, using singleton can reduce the memory pressure of the system and reduce GC.
2. a class only requires the generation of an object, such as a monitor in a class, the ID number of everyone.
3. Some classes occupy more resources when creating instances, or the instantiation takes a long time and is often used.
4. When a class needs frequent instantiation and the created objects are frequently destroyed, such as multi-threaded thread pool, network connection pool, etc.
5. Objects that frequently access databases or files.
6. For some control hardware level operations, or from the system point of view, they should be single control logic operations. If there are multiple instances, the system will be completely disordered.
7. When the object needs to be shared. Since singleton mode allows only one object to be created, sharing the object can save memory and speed up object access. Such as the configuration object in the Web, the connection pool of the database, etc.

Keywords: Java Design Pattern Singleton pattern

Added by name1090 on Tue, 08 Mar 2022 03:28:20 +0200