Java-Singleton design pattern

Design pattern
Design pattern refers to the optimal code structure, programming style, and problem-solving way of thinking after a lot of practice is summarized and theorized. This model helps us to think and explore again, just like a "routine."

Explanation of the singleton design pattern The
so-called singleton design pattern of a class is to take a certain method to ensure that in the entire software system, there can only be one object instance for a certain class, and the class only provides a method to obtain its object instance .

The realization of the
singleton design pattern The singleton design pattern is divided into hungry style and lazy style

1. Hungry Chinese style:
① First, create a constructor for the privatization class

//必须为private权限修饰
private Person(){
    
    
}

②Internally create objects of the class

//要求此对象也必须声明为静态的
private static Person instance = new Person();

③Provide a public static method to return the object of the class

public static Person getInstance(){
    
    
		return instacne;
	}

④Benefits: thread is safer Disadvantages: object loading time is too long

2. The lazy man's style
①The first step is the same as the hungry man's style, creating a private construction method for the
class ②Declaring the current class object, but not initializing it

//此对象也必须声明为static的
private static Order instance = null;

③Declare public and static methods to return the current class object

public static Order getInstance(){
    
    
		//如果没有对象就创建一个
        if (instance == null) {
    
    
            instance = new Order();
        }
        return instance;
    }

④Benefits: delay the creation of objects. Disadvantages: the current writing method is not thread safe, and it will be locked in the later multi-threading (affecting performance) or rewriting static internal classes.
⑤Finally, the test shows that the object is one and the address is the same

Advantages
of the singleton mode : Since the singleton mode only generates one instance, the system performance overhead is reduced. When the generation of an object requires more resources, such as reading the configuration and generating other dependent objects, it can be started by the application When generating a singleton object directly, and then permanently resident in memory to solve the problem.

Application scenarios
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_30068165/article/details/114382876