栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【设计模式】单例模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【设计模式】单例模式

单例设计模式

单例模式主要是为了避免因为创建了多个实例造成资源的浪费,且多个实例由于多次调用容易导致结果出现错误,而使用单例模式能够保证整个应用中有且只有一个实例。

  • 定义:
    • 私有化该类的构造函数
    • 通过new在本类中创建一个本类对象
    • 定义一个公有的方法,将在该类中所创建的对象返回
  • 属于创建型模式
饿汉式
  • 非懒加载
  • 线程安全
  • 实现简单
public class Singleton {

    private Singleton() {
    }

    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
        return instance;
    }

}
懒汉式 线程不安全
  • 懒加载
  • 线程不安全
  • 实现简单
public class Singleton {

    private Singleton() {
    }

    private static Singleton instance;

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

}
线程安全
  • 懒加载
  • 线程安全
  • 实现简单
public class Singleton {

    private Singleton() {
    }

    private static Singleton instance;

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

}

双重校验锁
  • 懒加载
  • 线程安全
public class Singleton {

    private volatile static Singleton instance;

    private Singleton() {
    }

    public static synchronized 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 SingletonEnum {

    instance;

    private SingletonEnum(){}

    public void whateverMethod(){

    }

    // 使用
    // SingletonEnum.instance.whateverMethod();

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/956832.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号