Singleton design pattern of Java

What is a design pattern?

Design pattern is the code structure, programming style and thinking way to solve problems after summarizing and theorizing in a large number of practice. The design pattern is like a classic chess score. In different chess games, we use different chess scores, which eliminates our own thinking and exploration.

The so-called singleton mode is to take certain methods to ensure that there can only be one object instance for a class in the whole software system, and the class only provides a method to obtain its object instance. If we want a class to produce only one object in a virtual machine, we must first set the access permission of the class constructor to private. In this way, you can't use the new operator to generate class objects outside the class. However, objects of this class can still be generated inside the class. Because the object of the class cannot be obtained outside the class, you can only call a static method of the class to return the object created inside the class. The static method can only access the static member variables in the class. Therefore, the variables pointing to the object of the class generated inside the class must also be defined as static.

Why use singleton mode?

New an object takes too much time; Need to use an object frequently;

Russian Chinese singleton mode: first create an object, and then use it directly when someone needs it;

Single. java

Test. java

Lazy singleton mode: first initialize the object to null, and then create a new object when the object needs to be used. Later, only this object will be used;

Single. java

Test. java

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>