设计模式-单例模式

  • 类型:创建型。
  • 目的:杜绝相同对象的反复创建,提升系统性能。

话不多说,直接看实现方案例。

实现案例

项目启动时加载

public class Test {
    private static Test ins = new Test();
    public static Test instance() {
        return ins;
    }
}

在项目启动时就被加载 → 项目启动变慢
如果对象不经常使用的话还存在浪费资源的问题。

懒加载,在使用时才被加载

public class Test {
    private static Test ins;

    public static synchronized Test instance() {
        if (ins == null) ins = new Test();
        return ins;
    }
}

在项目启动时并不加载 → 项目加载变快
第一次使用时加载 → 存在第一次使用时等待过长的问题
使用synchronized方法 → 性能下降

懒加载,在使用时才被加载(解决并发的性能问题)

public class Test {
    private static Test ins;

    public static Test instance() {
        if (ins == null) {
            synchronized (Test.class) {
                if (ins == null) ins = new Test();
            }
        }
        return ins;
    }
}

在项目启动时并不加载 → 项目加载变快
第一次使用时加载 → 存在第一次使用时等待过长的问题
使用双重判断方法 → 相对优化前性能提升
不推荐使用

懒加载,在使用时才会被加载(无并发性能问题)

public class Test {
    private static Singleton {
        private static final Test ins = new Test();
    }

    public static Test instance() {
        return Singleton.ins;
    }
}

在项目启动时并不加载 → 项目加载变快
第一次使用时加载 → 存在第一次使用时等待过长的问题
推荐使用

public enum Test {
    INSTANCE;

    public static Test instance() {
        return INSTANCE;
    }
}

在项目启动时就被加载 → 项目启动变慢
如果对象不经常使用的话还存在浪费资源的问题。
推荐使用

Original: https://www.cnblogs.com/spoonb/p/16703313.html
Author: spoonb
Title: 设计模式-单例模式

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/685834/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球