美文网首页
【设计模式】——单例模式(其他类型)

【设计模式】——单例模式(其他类型)

作者: 从不打小怪兽 | 来源:发表于2020-06-15 13:19 被阅读0次

双重检测锁式

  • 这个模式将同步内容下方到if内部,提高了执行效率,不必每次获取对象都要进行同步,只有第一次才同步,创建了以后就没必要了。
/**
 * 双重检查锁
 * @author admin
 *
 */
public class SingletonPattern03 {
    
    private static SingletonPattern03 st3=null;
    
    private SingletonPattern03() {
    }
    
    public static SingletonPattern03 getInstance() {
        
        if(st3==null) {
            SingletonPattern03 sp;
            
            synchronized (SingletonPattern03.class) {
                
                sp=st3;
                
                if(sp==null) {
                    synchronized (SingletonPattern03.class){
                        if(sp==null) {
                            sp=new SingletonPattern03();
                        }
                    }
                    st3=sp;
                }
                
            }
        }
        return st3;
    }
    
    
}

问题:由于编译器优化原因和JVM底层内部模型原因,偶尔会出问题,不建议使用--->看这个其他类的说明

静态内部类(也是一种懒加载的方式)

  • 要点
    • 外部类没有static属性,则不会像饿汉式那样立即加载对象。
    • \color{red}{只有真正的调用getInstance(),才会加载静态内部类。}加载类时是线程安全的。static final类型,保证内存只有一个实例存在,而且只能被赋值一次。
    • 兼备了并发高效调用和延时加载的优势!
/**
 * 静态内部内
 * @author admin
 *
 */
public class SingletonPattern04 {
    
    //加载类时不会加载,真正调用的时候再加载。
    private static class SingletonInstacne{
        private static final SingletonPattern04 st4=new SingletonPattern04();
    }
    
    private SingletonPattern04(){
    }
    
    public static SingletonPattern04 getInstance(){
        return SingletonInstacne.st4;
    }
    
}

此时我没有啥想说的

枚举实现单例模式

  • 优点:
    • 实现简单
    • 枚举本身就是单例模式。由JVM从根本上提供保障!避免通过反射和反序列化的漏洞!
/**
 * 枚举式(没有延时加载)
 * @author admin
 *
 */
public enum SingletonPattern05 {
    INSTANCE;
    
    //可以添加需要的操作
    public void singletonOperation(){
    }
    
}

缺点:无延时加载

相关文章

网友评论

      本文标题:【设计模式】——单例模式(其他类型)

      本文链接:https://www.haomeiwen.com/subject/gebcxktx.html