从优化的角度思考单例模式

从优化的角度思考单例模式,第1张

从优化的角度思考单例模式
  1. 懒汉模式的优化(synchronize解决线程安全问题)
    package design_mode;
    
    
    public class SingletonSynchronized {
    
    
        private  static  SingletonSynchronized singletonSynchronized = null;
    
        private SingletonSynchronized(){
            System.out.println("线程安全的单例模式");
        }
    
        public static SingletonSynchronized getSingletonSynchronized(){
            synchronized (SingletonSynchronized.class){
                if ((singletonSynchronized == null)){
                    singletonSynchronized = new SingletonSynchronized();
                }
                return singletonSynchronized;
            }
        }
    }
    

  2. 双重锁认证进一步提高性能
    package design_mode;
    
    
    public class SingletonHight {
        private static SingletonHight singletonHight = null;
        private SingletonHight(){
            System.out.println("最终版单例模式");
        }
    
        public static SingletonHight getSingletonHight(){
            if(singletonHight==null){
                synchronized (SingletonHight.class){
                    if(singletonHight==null){
                        singletonHight = new SingletonHight();
                    }
    
                }
            }
            return singletonHight;
        }
    }
    
  3. 通过静态内部类实现单例模式的延迟加载和线程安全
         这种方式是通过静态内部类实现的,静态内部类只有在调用时才会加载,这样就保证了延迟初始化,但是遇到序列化对象时会失效。
public class SingletonInnerObject {
    private SingletonInnerObject(){};
    
    private static class InnerObject {
        private static SingletonInnerObject singletonInnerObject = new SingletonInnerObject();
    }
    
    public static SingletonInnerObject getInstance(){
        return InnerObject.singletonInnerObject;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5661355.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存