Common design patterns: one example pattern

Basic concept: ensure that a class has only one instance, and provide a global access point to access it.

1. Lazy (advantage: delay loading (load when needed), suitable for single thread operation
Disadvantages: thread is not safe, and it is easy to be out of sync in multithreading, such as frequent read and write operations on database objects.)

public class Singleton {  
    /* Hold the private static instance to prevent it from being referenced. The value here is null. The purpose is to delay loading */  
    private static Singleton instance = null;  
  
    /* Private constructor to prevent instantiation */  
    private Singleton() {}  
  
    /* 1:Lazy, static engineering methods, creating examples */  
    public static Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  
}

2. Dual thread check locking (DCL) mode (advantages: delayed loading, thread safety

Disadvantages: complicated writing, not concise)

public class SingletonInner {  
    private static volatile SingletonInner sInst = null;  //  volatile is added here Prevent reordering
  
    /** 
     * Private constructor 
     */  
    private SingletonInner() {}  
  
    public static SingletonInner getInstance() {  
        SingletonInner inst = sInst;  // Create temporary variables here
        if (inst == null) {
            synchronized (SingletonInner.class) {
                inst = sInst;
                if (inst == null) {
                    inst = new SingletonInner();
                    sInst = inst;
                }
            }
        }
        return inst;  // < note that temporary variables are returned here
    }
  
}  
3. Implementation of internal classes (advantages: delayed loading, thread safety (class loading in java is mutually exclusive), and memory consumption is also reduced. Internal classes are recommended.)

public class SingletonInner {  
    /** 
     * Inner class implements singleton mode 
     * Delay loading, reduce memory overhead   
     */  
    private static class SingletonHolder {  
        private static SingletonInner instance = new SingletonInner();  
    }  
  
    /** 
     * Private constructor 
     */  
    private SingletonInner() {}  
  
    public static SingletonInner getInstance() {  
        return SingletonHolder.instance;  
    }  
  
    protected void method() {  
        System.out.println("SingletonInner");  
    }  
} 

Tags: Database Java

Posted on Wed, 01 Apr 2020 14:03:10 -0700 by sinista