设计模式 - 单例模式(singleton pattern)

设计模式 - 单例模式(singleton pattern)

饿汉模式

public class Singleton{
    private static final Singleton singleton = new Singleton ();
    
    private Singleton () {}
    
    public static Singleton getInstance() {
        return singletion;
    }
} 

以上方式在加载类的过程中比较慢,以下方式可以懒加载

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

懒汉模式

需要通过双层空判断以及锁来确保线程安全与效率并存

public class Singleton {  
    private static Singleton singleton;  
      
    private Singleton() {}  
      
    public static Singleton getInstance() {  
        if (singleton == null) {  
            synchronized (Singleton.class) {  
                if (singleton == null) {  
                    singleton = new Singleton();  
                }  
            }  
        }  
        return singleton;  
    }  
}  

猜你喜欢

转载自blog.csdn.net/Sool179/article/details/85002313