Design Patterns - Singleton Pattern

Why use the singleton pattern?

There are some objects we only need one, for example: thread pool, cache, etc. If multiple objects are instantiated at the same time, there will be some problems.

For such a class, it is obviously unreliable to rely on the programmer not to instantiate by convention. 

 

Try: Create a class, make all methods and variables static, and use the class directly as a singleton.

Problem: Since control of static initialization is in Java's hands, doing so can lead to confusion, especially when there are many classes involved.

 

Try: use global variables instead of singleton pattern.

Problem: In Java, global variables are basically static references to objects. Disadvantage one, eager instantiation vs lazy instantiation. The second disadvantage is that there is no guarantee that there is only one instance.

What is the singleton pattern?

Definition : Ensures that a class has only one instance and provides a global access point.

 

How to use the singleton pattern?

Set the constructor to private, that is, only the class itself can call its own constructor;

Set a static method getInstance() for the class to create or get this instance.

Handling multithreading:

Method 1: Synchronize the getInstance() method, add the synchronize keyword directly to the method

Applicability: The getInstance() method is not run frequently, or performance is not critical.

Method 2: Eager instantiation, that is, creating a singleton in a static initializer, can ensure thread safety

public class Singleton{
    private static Singleton uniqueInstance=new Singleton();
    private Singleton(){}
    
    public static Singleton getInstance(){
        return uniqueInstance;
    }
)

Applicable situation: application always creates singleton, applies singleton very frequently

Method 3: Double Check Locking

public class Singleton{
    private volatile static Singleton uniqueInstance;//必须有volatile关键字,确保初始化成实例时,多个线程正确地处理该变量
    private Singleton(){}
    
    public static Singleton getInstance(){
        if(uniqueInstance==null){
            synchronized(Singleton.class){
                if(uniqueInstance==null){
                     uniqueInstance=new Singleton();
                }
             }
        }
        return uniqueInstance;
    }
)

Applicable variables: It can be used after java5, and the performance is very good.

Guess you like

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