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;
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值