Class and object creation mode - singleton mode

Singleton pattern----singleton object creation pattern

The singleton pattern ensures that there is only one instance of a class, and it instantiates itself and provides this instance to the entire system

question:

It turns out that instances are frequently created and destroyed during system operation, resulting in frequent memory jitters and a sharp drop in memory throughput.

Solution:

First, set your own constructor to private, and don't let others new your instance;

Second, provide a static method for others to get your instance, and you can just return the instance you created yourself in this method."

 

Divided into "lazy man style" ---- probably because it is created when needed, it seems very "lazy".

The implementation executes the getInstance() method first, and then executes the constructor method when it is called for the first time.

 

"Hungry Chinese style" -- probably because it was too hungry, the object was created as soon as it came up

The implementation executes the constructor first, and then executes the getInstance() method on the first call. 

Moreover, the hungry Chinese style is a thread-safe way of writing.

 

In fact, we can use different singleton patterns according to different usage scenarios. If we need to pass in parameters in the getInstance() method to assist in the initialization of the constructor, we have to use lazy style .

In other cases, you need to use "Hungry Chinese Style"

 

The singleton pattern has the following characteristics:
  1. A singleton class can only have one instance.
  2. A singleton class must create its own unique instance by itself.
  3. The singleton class must provide this instance to all other objects.
  The singleton pattern ensures that there is only one instance of a class , and that it instantiates itself and provides this instance to the entire system. In computer systems, the driver objects of thread pools , caches , log objects , dialog boxes, printers, and graphics cards are often designed as singletons. These applications all have the function of resource manager more or less . Each computer can have several printers, but only one Printer Spooler to avoid two print jobs being output to the printer at the same time. Each computer can have several communication ports, and the system should manage these communication ports centrally to avoid a communication port being called by two requests at the same time. In short, the choice of the singleton mode is to avoid inconsistent states and avoid political bulls .

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325689678&siteId=291194637