单例模式有哪些

1、懒汉式

public class Singleton2 {
    
    

    private static Singleton2 instance;

    private Singleton2() {
    
    }

    public static synchronized Singleton2 getInstance() {
    
    
        if (instance == null) {
    
    
            instance = new Singleton2();
        }

        return instance;
    }

}

2、饿汉式

public class Singleton3 {
    
    

    private static Singleton3 instance = new Singleton3();

    private Singleton3() {
    
    }

    public static Singleton3 getInstance() {
    
    
        return instance;
    }

} 

3、双重锁式

public class Singleton7 {
    
    

    private static volatile Singleton7 instance = null;

    private Singleton7() {
    
    }

    public static Singleton7 getInstance() {
    
    
        if (instance == null) {
    
    
            synchronized (Singleton7.class) {
    
    
                if (instance == null) {
    
    
                    instance = new Singleton7();
                }
            }
        }

        return instance;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_44752641/article/details/114777169