创建型---单例模式

单例模式

核心作用

  • 保证一个类只有一个实例,并且提供一个访问该类的全局访问点。

单例模式的优点

  • 由于单例模式只生成一个实例,减少系统性能开销。
  • 单例模式可以在系统设置全局的访问点,优化共享资源访问。

单例模式的特点

  • 类构造器私有
  • 持有自己类型的属性
  • 对外提供获取实例的静态方法

常见的五种单例模式实现方式

  1. 饿汉式(线程安全,调用效率高,不能延时加载)
public class Singleton {  
    private static Singleton instance = new Singleton();  
    private Singleton (){}  
    public static Singleton getInstance() {  
    return instance;  
    }  
}

  1. 懒汉式(线程安全,调用效率不高,可以延时加载)
public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
  
    public static synchronized Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}

  1. DCL懒汉式(线程安全,调用效率高,可以延时加载,但由于JVM底层内部模型的原有,偶尔会出现问题,不建议使用)
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;  
    }  
}

  1. 饿汉式改进:静态内部类式(线程安全,调用效率高,可以延时加载)
public class Singleton { 
    private Singleton(){
    }
      public static Singleton getInstance(){  
        return Inner.instance;  
    }  
    private static class Inner {  
        private static final Singleton instance = new Singleton();  
    }  
} 

  1. 枚举单例(线程安全,调用效率高,不能延时加载)
public enum Singleton  {
    INSTANCE 
    //doSomething 该实例支持的行为
    //可以省略此方法,通过Singleton.INSTANCE进行操作
    public static Singleton get Instance() {
        return Singleton.INSTANCE;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。