单列模式(Singleton) - 隐藏问题

  • 懒汉模式

public class LazySingleton {

    private static LazySingleton lazySingleton = null;

    private LazySingleton(){}

    public static synchronized LazySingleton getLazySingleton(){
        if(lazySingleton == null){
            lazySingleton = new LazySingleton();
        }
        return lazySingleton;
    }

}

 

  • 饿汉模式

public class EagerSingleton {

    private static EagerSingleton eagerSingleton = new EagerSingleton();

    private EagerSingleton(){}

    public static EagerSingleton getEagerSingleton(){
        return eagerSingleton;
    }
}
  • 双重锁 单列模式(不建议使用)

public class Singleton {

    private static Singleton instance = null;

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

    private Singleton(){}
}
  • 静态内部类实现单列模式,执行效率更优

public class SingletonDemo1 {

    private static class SingletonClassInstance{
        private static final SingletonDemo1 instance = new SingletonDemo1();
}
    public static SingletonDemo1 getInstance(){
        return SingletonClassInstance.instance;
    }
    private SingletonDemo1(){}
}
  • 枚举实现单列模式  简单效率高,避免反射和反序列化的漏洞

public enum SingletonDemo2 {

    INSTANCE;

    //添加自己需要的操作
    public void singletonOperation(){

    }
}
  • 单列如何防止反射和反序列化漏洞

    public class SingletonDemo3 implements Serializable {
    
        private static SingletonDemo3 instance;
    
        private SingletonDemo3(){
            if(instance != null){
                throw new RuntimeException();
            }
        }
    
        public static SingletonDemo3 getInstanc(){
            if(instance  == null){
                instance = new SingletonDemo3();
            }
            return instance;
        }
    
        // 反序列时,直接调用此方法
        private Object readResolve() throws ObjectStreamException{
            return instance;
        }
    }

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值