设计模式(单例)

  • 作用:保证1个类只能创建1个实例,并且该类提供1个访问该实例的全局访问点
  • 优点:减少系统性能开销

饿汉式(线程安全、调用效率高、不能延时创建):

public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

懒汉式(线程安全、调用效率低、能延时创建):

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

双重校验锁(double-checked locking):

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

静态内部类实现方式(线程安全、调用效率高、能延时创建):

public class Singleton {
    private static class SingletonHolder {
        private static final Singleton instance = new Singleton();
    }

    private Singleton() {}

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }
}

枚举实现单例(不能延迟创建):

public enum Singleton {

    INSTANCE;

    // 添加自己需要的操作
    public void singletonOperation() {}
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 单例模式(Singleton Pattern)是众多设计模式中较为简单的一个,同时它也是面试时经常被提及的问题,如...
    廖少少阅读 601评论 0 1
  • 单例模式 介绍 为了节约系统资源,有时需要确保系统中某个类只有唯一一个实例,当这个唯一实例创建成功之后,我们无法再...
    666真666阅读 360评论 0 6
  • 核心作用: 保证一个类只有一个实例,并且提供一个访问该实例的全局访问点 常见应用场景: Windows的Task ...
    GaaraZ阅读 402评论 0 0
  • 概念 单例模式的主要作用是保证在程序中,某个类只有一个实例存在,一些管理器和控制器常被设计成单例子模式 单例模式写...
    niknowzcd阅读 151评论 0 0
  • 美好的一天开始了
    vivian926阅读 152评论 1 1