单例模式

应用场景

当我们仅需要一个类仅有一个实例,并提供一个访问它的全局访问点,就可以使用单例模式来减少频繁的创建和销毁

优点

  • 减少性能开支
  • 避免对资源的多重占用,比如多个对象去读写一个文件
  • 优化和共享资源访问

实例

懒汉式

  • 延迟初始化(懒加载)
  • 线程不安全
public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
  
    public static Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}

饿汉式

  • 线程安全
  • 可能产生垃圾对象
public class Singleton {  
    private static Singleton instance = new Singleton();  
    private Singleton (){}  
    public static Singleton getInstance() {  
    return instance;  
    }  
}

登记式/静态内部类

  • 是饿汉式的改进
  • 线程安全
  • 延迟加载
public class Singleton {  
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
    return SingletonHolder.INSTANCE;  
    }  
}

双检锁/双重校验锁(DCL,即 double-checked locking)

  • 懒加载
  • 线程安全
public class Singleton {  
    private volatile static Singleton singleton;  
    private Singleton (){}  
    public static Singleton getSingleton() {  
    if (singleton == null) {  
        synchronized (Singleton.class) {  
        if (singleton == null) {  
            singleton = new Singleton();  
        }  
        }  
    }  
    return singleton;  
    }  
}

枚举

  • 实现单例的最佳模式
  • 自动支持序列化机制
public enum Singleton {  
    INSTANCE;  
    public void whateverMethod() {  
    }  
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容