Java 单例模式实现

饿汉式

线程安全,调用效率高,但是不能延时加载。

public class Singleton {

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

懒汉式

调用效率不高,但是能延时加载。

如果方法没有 synchronized,单例没有 volatile , 则线程不安全。

public class Singleton {

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

懒汉式改良

线程安全,使用了 double-check-lock(双重检查锁),即check-lock-check,目的是为了减少同步的开销。

volatile关键字来修饰 instance,其最关键的作用是防止指令重排。

public class Singleton {

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

静态内部类实现

线程安全,调用效率高,可以延时加载。静态内部类不会在 Singleton 类加载时就加载,而是在调用 getInstance() 方法时才进行加载,达到了懒加载的效果。

public class Singleton {
    
    private Singleton() {}
    
    public static Singleton getInstance(){
        return SingletonFactory.singletonInstance;
    }
    
    private static class SingletonFactory{
        private static Singleton singletonInstance = new Singleton();
    }
}

枚举实现

线程安全,调用效率高,不能延时加载,可以天然的防止反射反序列化调用。

public enum Singleton {

    INSTANCE;

    private String instance;

    Singleton() {
        instance = new String("singleton");
    }

    public String getInstance(){
        return instance;
    }
}
发布了19 篇原创文章 · 获赞 21 · 访问量 511

猜你喜欢

转载自blog.csdn.net/siriusol/article/details/104398712
今日推荐